0
public class override {

    public static void main(String[] args) {
        c1 obj = new c1();
        System.out.println(obj);
    }
}

class a1 {
    public String toString (){
        return "this is clas a";
    }
}

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";
    }
    
}

I need to access the superclass a1 toString method in c1 subclass. Is there any way to do it. I'm learning java, any help would be a great support.

fmatt
  • 464
  • 1
  • 5
  • 15
Asok M
  • 25
  • 5

2 Answers2

0

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() {...}
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

You would probably like to have something as super.super.toString(). But this is not allowed in java. So you can simply use it twice as bellow :

public class override {

    public static void main(String[] args) {
        c1 obj = new c1();
        System.out.println(obj);
    }
}

class a1 {
    public String toString (){
        return "this is clas a";
    }
}

class b1 extends a1{
    public String toString (){
        return "this is clas b";
    }

    public String superToString(){
        return super.toString();
    }
}

class c1 extends b1{
    public String toString (){
        return super.superToString() + "\nthis is clas c";
    }
}

This Question may also help.

fmatt
  • 464
  • 1
  • 5
  • 15