Reputation: 968
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?
Upvotes: 1
Views: 28
Reputation: 393841
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;
}
}
Upvotes: 2