Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Name ambiguity between outer and inner class methods

Suppose I have:

public class OuterClass() {

  public class InnerClass {
    public void someMethod(int x) {
      someMethod(x);
    }
  }

  public void someMethod(int x) {
    System.out.println(x);
  }
}

How do I resolve the ambiguity between the someMethod() of the outer class and the someMethod() of the inner class?

like image 406
Jake Avatar asked Sep 25 '09 18:09

Jake


3 Answers

You can refer to the outer with OuterClass.this, or call the method with OuterClass.this.method().

However, as a point of design, sharing the name is confusing, to say the least. It might be reasonable if the inner class represented an extension or, say, a concrete implementation of an abstract method, but that would be clearer by calling super.method. Calling a super method directly, (as it looks like you're intending to do?), is confusing.

like image 180
Steve B. Avatar answered Nov 11 '22 06:11

Steve B.


Scope it to the outer class with OuterClass.this.someMethod():

public class OuterClass {

  public class InnerClass {

    public void someMethod(int x) {
      OuterClass.this.someMethod(x);
    }
  }

  public void someMethod(int x) {
    System.out.println(x);
  }
}
like image 39
SingleShot Avatar answered Nov 11 '22 08:11

SingleShot


Renaming ambiguity is a good practice. Especially if you apply it in the upward and backward architecture.

like image 1
Roman C Avatar answered Nov 11 '22 06:11

Roman C