简体   繁体   中英

Using, if applicable, the subclass' method

I have the following code:

public class A {
    private boolean val(){
        return true;
    }

    protected boolean test(){
        return val();
    }
}

public class B extends A {
    private boolean val(){
        return false;
    }
}

public class C {
    public static void main(String[] args){
        B b = new B();
        System.out.println(b.test());
    }
}

It returns true because the test() method in A calls A's val(). After some research, I understood that this is expected in Java. However, I would like test() to print false when called from B, and true when called from A. Is it possible to do that?

The reason your code calls A 's val() and not B 's val() is that the val() method has private access modifier and therefore cannot be overridden. Change the access modifier to protected .

public class A {
    protected boolean val(){
        return true;
    }

    protected boolean test() {
        return val();
    }
}

public class B extends A {
    protected boolean val() {
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM