Using, if applicable, the subclass' method

Stubborn :

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?

Eran :

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;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=409659&siteId=1