In Java, how do I call a base class's method from the overriding method in a derived class?

后端 未结 12 871
無奈伤痛
無奈伤痛 2020-11-27 02:50

I have two Java classes: B, which extends another class A, as follows :

class A {
    public void myMethod() { /* ... */ }
}

class B extends A {
    public          


        
相关标签:
12条回答
  • 2020-11-27 02:58

    If u r using these methods for initialization then use constructors of class A and pass super keyword inside the constructor of class B.

    Or if you want to call a method of super class from the subclass method then you have to use super keyword inside the subclass method like : super.myMethod();

    0 讨论(0)
  • 2020-11-27 03:01

    I am pretty sure that you can do it using Java Reflection mechanism. It is not as straightforward as using super but it gives you more power.

    class A
    {
        public void myMethod()
        { /* ... */ }
    }
    
    class B extends A
    {
        public void myMethod()
        {
            super.myMethod(); // calling parent method
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:06
    // Using super keyword access parent class variable
    class test {
        int is,xs;
    
        test(int i,int x) {
            is=i;
            xs=x;
            System.out.println("super class:");
        }
    }
    
    class demo extends test {
        int z;
    
        demo(int i,int x,int y) {
            super(i,x);
            z=y;
            System.out.println("re:"+is);
            System.out.println("re:"+xs);
            System.out.println("re:"+z);
        }
    }
    
    class free{
        public static void main(String ar[]){
            demo d=new demo(4,5,6);
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:08

    See, here you are overriding one of the method of the base class hence if you like to call base class method from inherited class then you have to use super keyword in the same method of the inherited class.

    0 讨论(0)
  • 2020-11-27 03:11

    The keyword you're looking for is super. See this guide, for instance.

    0 讨论(0)
  • 2020-11-27 03:12
    class test
    {
        void message()
        {
            System.out.println("super class");
        }
    }
    
    class demo extends test
    {
        int z;
        demo(int y)
        {
            super.message();
            z=y;
            System.out.println("re:"+z);
        }
    }
    class free{
        public static void main(String ar[]){
            demo d=new demo(6);
        }
    }
    
    0 讨论(0)
提交回复
热议问题