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