Java Inheritance - calling superclass method

前端 未结 5 1259
遥遥无期
遥遥无期 2020-11-27 18:15

Lets suppose I have the following two classes

public class alpha {

    public alpha(){
        //some logic
    }

    public void alphaMethod1(){
        /         


        
5条回答
  •  佛祖请我去吃肉
    2020-11-27 18:43

    It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

    If it depends on the situation, you can put some code logic like :

    public void alphaMethod1(){
        if (something) {
            super.alphaMethod1();
            return;
        }
        // Rest of the code for other situations
    }
    

    Like this it will only call A's method when needed and will remain invisible for the class user.

提交回复
热议问题