+ 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 odpowiedzi
+ 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