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(){
}
}
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.
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.
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.
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:
You can just use B.super.getCount()
to call A.getCount()
in call()
.
You've to use B.super.getCount()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With