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

后端 未结 12 864
無奈伤痛
無奈伤痛 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 03:13

    Just call it using super.

    public void myMethod()
    {
        // B stuff
        super.myMethod();
        // B stuff
    }
    
    0 讨论(0)
  • 2020-11-27 03:15

    super.MyMethod() should be called inside the MyMethod() of the class B. So it should be as follows

    class A {
        public void myMethod() { /* ... */ }
    }
    
    class B extends A {
        public void myMethod() { 
            super.MyMethod();
            /* Another code */ 
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:15

    Use the super keyword.

    0 讨论(0)
  • 2020-11-27 03:19
    super.baseMethod(params);
    

    call the base methods with super keyword and pass the respective params.

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

    call super.myMethod();

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

    Answer is as follows:

    super.Mymethod();
    super();                // calls base class Superclass constructor.
    super(parameter list);          // calls base class parameterized constructor.
    super.method();         // calls base class method.
    
    0 讨论(0)
提交回复
热议问题