Java: Name ambiguity between outer and inner class methods
Asked Answered
S

3

6

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?

Swinford answered 25/9, 2009 at 18:41 Comment(0)
A
13

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.

Aretino answered 25/9, 2009 at 18:44 Comment(0)
Z
6

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);
  }
}
Zinn answered 25/9, 2009 at 18:45 Comment(1)
Aw... Steve B. posted the same answer just before me. I will leave mine here for the example code.Zinn
C
1

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

Clarkia answered 6/8, 2012 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.