Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java instance variable and method having same name

Tags:

java

In java can an instance variable and a method have the same name without any instability or conflict?

I want to make sure if I can get away with compiling it, that it wont cause any error down the road.

like image 527
rubixibuc Avatar asked Mar 31 '12 23:03

rubixibuc


People also ask

Can method and instance variable have same name?

Yes it's fine, mainly because, syntactically , they're used differently.

What happens when the parameter has the same name as an instance variable?

There's no problem with giving parameter names and instance variable names the same name. But Java has to pick whether it is an instance variable or a parameter variable. Either way, it doesn't do what you think it should do. It doesn't initialize the instance variables with the values of the parameter variables.

Can a local variable have the same name as an instance variable?

Yes you can, but local variable will hide the class variable.

Can a method have the same name as a field in Java?

Java static code analysis: Methods and field names should not be the same or differ only by capitalization.


2 Answers

Yes it's fine, mainly because, syntactically , they're used differently.

like image 96
Caffeinated Avatar answered Oct 10 '22 21:10

Caffeinated


It's completely fine because methods and variables are called differently.

Code:

String name = "myVariable";

public String name() {
    return "myMethod";
}

System.out.println(name()); // Brackets for method call
System.out.println(name); // No brackets for variable call

Output:

myMethod

myVariable

like image 34
JREN Avatar answered Oct 10 '22 21:10

JREN