Basically you can't - you can't access "grandparent" directly, only via the parent if it allows you to do that.
Class b1
has a toString
definition that doesn't call super.toString
so its class b1
that has decided to "override" the functionality of the grandparent's (a1) toString
method. Since class c1
extends b1
- you "see" only this overridden version and not the version of toString
of a1
.
Now practically if you need this piece of functionality (lets pretends that its not toString but some code that can be required from all the children, you can do the following:
class a1 {
protected String commonReusableMethod() {
return "this is clas a";
}
public String toString (){
return commonReusableMethod();
}
}
class b1 extends a1{
public String toString (){
return "this is clas b";
}
}
class c1 extends b1{
public String toString (){
return super.toString() + "\nthis is clas c" + "\n" +
commonReusableMethod(); // you can call this method from here
}
}
Note the definition of commonReusableMethod
- it is protected
so you can call it from anywhere in the hierarchy (from a1
, b1
, c1
)
If you don't want to allow overriding this protected method, add also final
:
protected final commonReusableMethod() {...}