+ 1

same name defined for method and object?

public class MyClass { public static void main(String[] args) { Car Car1 = new Car(); // to be removed System.out.println(Car1.Brand); } } class Car1 { static String Brand = ā€œToyotaā€; } // class to be removed class Car() { String Brand = ā€œAudiā€; } === Now I have learnt a few types of entity (or ā€œthingā€? I don’t know how to call them…), namely object, class, method and variable/attribute. If I give the same type of ā€œthingā€ the same name, it looks like Eclipse will warn me about this (like, when I created two classes named ā€œCarā€, an error message will be shown. I did not test other types of ā€œthingsā€ though). I then suspected what would happen if I name different types of things the same name. In the above example, I name a class Car1 (attaching a static label ā€œToyotaā€), but at the same time, name an object Car1 (attaching a label ā€œAudiā€) as well, which was created from another class Car(). When I print the label, ā€œAudiā€ poped up and it looks like ā€œToyotaā€ was overidden. To make sure I did not write the syntax wrong, I deleted the parts indicated above and re-ran the program, and ā€œToyotaā€ poped up. So my questions are: 1. Why does the object takes over the class when calling the expression ā€œCar1.Brandā€? In what order does java consider in this situation? 2. Why wasn’t any warning shown for this?

11th Aug 2016, 8:48 AM
Ka Ho Hui
Ka Ho Hui - avatar
2 Answers
+ 2
1. I think local variable is first priority. 2. It is about Java naming convention. If we follow it, the variable should be named using lowerCamelCase like car1(not Car1). So the name is not be the same. But it is not rule and not forced us to follow. However, I am not sure if the eclipe plugin like FindBugs will help in this case. Let's try. https://marketplace.eclipse.org/content/findbugs-eclipse-plugin
11th Aug 2016, 12:26 PM
WPimpong
WPimpong - avatar
+ 1
In simpler words local variable holds priority. same goes for methods too..in this case for object
11th Aug 2016, 8:39 PM
Abhinav