Muhammad Rokonuzzaman
Muhammad Rokonuzzaman

Reputation: 131

How do I access Super class variables and methods in main method?

    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)?

Upvotes: 1

Views: 756

Answers (2)

Aakash Wadhwa
Aakash Wadhwa

Reputation: 91

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

Upvotes: -1

Always Learning
Always Learning

Reputation: 2743

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

Upvotes: 2

Related Questions