1
    class Main
{
    public static void main(String[] arg)
    {
        C c = new C();

        c.show(); //how to access class A
    }

}

class A
{
    void show()
    {
    System.out.println("inside A");
    }
}

class B extends A
{
    void show()
    {
        System.out.println("inside B");
    }
}

class C extends B
{
    void show()
    {
        super.show(); //How to access class A
        System.out.println("inside C");
    }
}

Using super I can access Super Class variables and methods like C can access B's methods but what if I want to access A's methods in C. How do I do that in simple way like using super? Like two super should do the trick... And how do I access Class A method only by allocating Class C(if name-hiding present)?

2 Answers2

2

There is no construct in Java to do something like c.super.super.show() as it violates encapsulation. The Law of Demeter is a good principle illustrating why this is rightly avoided. Taking this into account, the way you can do what you request within Java is to expose a.show() in b like this:

class Main
{
    public static void main(String[] arg)
    {
        C c = new C();

        c.show(); //how to access class A
    }

}

class A
{
    void show()
    {
        System.out.println("inside A");
    }
}

class B extends A
{
    void show()
    {
        System.out.println("inside B");
    }

    void showA()
    {
        super.show();
    }
}

class C extends B
{
    void show()
    {
        super.showA(); // Calls A
        System.out.println("inside C");
    }
}
Always Learning
  • 2,623
  • 3
  • 20
  • 39
-1

One way of using A's show() method in C is by creating class A object in C and using A's show function.

class C extends B
{
    void show()
    {
        new A().show();
        super.show();
        System.out.println("inside C");
    }
}
Aakash Wadhwa
  • 91
  • 1
  • 2
  • 11
  • This assumes `show` is static, or at least can be treated as static. – Jackson Apr 18 '18 at 03:56
  • `show` is not static , it is just creating temporary object and calling A's function – Aakash Wadhwa Apr 18 '18 at 03:59
  • You're treating `show` as static by implying you can substitute a call to a different object's `show` in place of this object's. This is only a valid assumption if `show` does not rely on the individual object's properties, and thus can be treated as static. – Jackson Apr 18 '18 at 04:01