Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Local Nested Classes and accessing super methods

I have following class hierarchy scenario; Class A has a method and Class B extends Class A, where I want to call a method from super class from a locally nested class. I hope a skeletal structure picture the scenario more clearly Does Java permit such calls?

class A{
  public Integer getCount(){...}
  public Integer otherMethod(){....}
}

class B extends A{
  public Integer getCount(){
    Callable<Integer> call  = new Callable<Integer>(){
      @Override
      public Integer call() throws Exception {
         //Can I call the A.getCount() from here??
         // I can access B.this.otherMethod() or B.this.getCount()
         // but how do I call A.this.super.getCount()??
         return ??;
      }
   }
    .....
  }
  public void otherMethod(){
  }
}
like image 697
sachink Avatar asked Jan 13 '12 16:01

sachink


People also ask

What is a nested class in Java?

In java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code.

Does class nestedclass exist independently of class outerclass?

Thus in above example, class NestedClass does not exist independently of class OuterClass. A nested class has access to the members, including private members, of the class in which it is nested. However, the reverse is not true i.e., the enclosing class does not have access to the members of the nested class.

What is the use of Super class in Java?

Super refers to an object of the parent class. (Refer to this article). We can invoke the overridden method of the parent class with the help of the super keyword. super () is used for executing the constructor of the parent class and should be used in the first line in the derived class constructor.

Can a static class have a nested method?

And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. They are accessed using the enclosing class name. For example, to create an object for the static nested class, use this syntax:


2 Answers

You can just use B.super.getCount() to call A.getCount() in call().

like image 113
Ernest Friedman-Hill Avatar answered Sep 16 '22 19:09

Ernest Friedman-Hill


You've to use B.super.getCount()

like image 20
adarshr Avatar answered Sep 20 '22 19:09

adarshr