rubixibuc
rubixibuc

Reputation: 7427

java instance variable and method having same name

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.

Upvotes: 30

Views: 27259

Answers (5)

Pcgomes
Pcgomes

Reputation: 312

I actually have ran into an issue, which is very specific. It just manifests itself in Java 8 (using Nashorn), but not in Java 6 (using Rhino). If it try to access an instance variable of a Java object via Javascript, the [] operator returns the method instance instead.

Let's suppose I'm running the following Java declaration:

class MyClass {
    private boolean isSet=false;
    public boolean isSet() { return isSet; }
}

If I manipulate an object of such class in Javascript, and then try to access it with [] operator, I get the method reference.

var obj = new MyClass();
var myfields = (myclass.getClass()).getDeclaredFields();
var myfieldname = myfields[0].name;

// The following prints the method declaration, not the boolean value:
// [jdk.internal.dynalink.beans.SimpleDynamicMethod boolean MyClass.isSet()]
println( obj[myfieldname] );

UPDATE: Apparently Nashorn's method overloading resolution mechanism ("implicitly" or non-intentionally) gives higher precedence to methods without arguments over instance fields with the same name.

Upvotes: 5

MathiasTCK
MathiasTCK

Reputation: 329

You can, but it is an anti pattern, should be avoided, and can be caught by analytics like so:

http://pmd.sourceforge.net/pmd-4.3.0/rules/naming.html

Upvotes: 3

Code Enthusiastic
Code Enthusiastic

Reputation: 2847

The only conflict I could think of is

int sameName = 5;

public int sameName() {
  //method body
  return 100;
}

If you write "this.sameName" when you are supposed to write "this.sameName()" and vice-versa at some place in the program then annihilation of the code has just begun.

Upvotes: 4

Caffeinated
Caffeinated

Reputation: 12484

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

Upvotes: 32

JREN
JREN

Reputation: 3630

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

Upvotes: 9

Related Questions