Hi

Can any one tell me how to call a subclass method from a superclass?
For example:
I have a class A,B and C. Now B and C extends A.
So is there any way that we can call a method of B in A?


Thanks
Abhishek

Hi

Can any one tell me how to call a subclass method from a superclass?
For example:
I have a class A,B and C. Now B and C extends A.
So is there any way that we can call a method of B in A?


Thanks
Abhishek

Well depending on whether or not the extending classes are static or non-static-the same applies for your methods within these classes-there are many different ways to access them. Here is a sample i made to try help you:

public class X {
    
    public static void main(String[] args) {
        Y.methodY1();//calling static method from a static class Y methodY1()
        
        Y classB = new Y();
        classB.methodY2();//calling a non-static method from static class Y methodY2()
        // new Y().methodY2();//another way to call methodY2-just an extension of the above
        
        X classA = new X();
        classA.new Z().methodZ1();//calling a non-static method from non-static class Z methodZ1()
        //new X().new Z().methodZ1();//another way to call methodZ1 -just an extension of the above
        
    }
    
    static class Y {
        
        private static void methodY1() {
        }
        
        private void methodY2() {
        }
    }
    
    class Z {
        
        private void methodZ1() {
        }
    }
}

Edited 4 Years Ago by DavidKroukamp: n/a

Hi
I have a class A,B and C. Now B and C extends A.
So is there any way that we can call a method of B in A?

possible? off course.
but ... a bit fishy.

this would imply that A knows the type (whether) or not it inherits A or not.

but why exactly do you need something like this? sometimes knowing the reason why doing something makes it a lot easier to respond, and it might help us give the correct answer you are looking for.

This article has been dead for over six months. Start a new discussion instead.