[英]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().它返回 true,因为 A 中的 test() 方法调用了 A 的 val()。 After some research, I understood that this is expected in Java.
经过一番研究,我了解到这是 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?
但是,我希望 test() 在从 B 调用时打印 false,从 A 调用时打印 true。可以这样做吗?
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.您的代码调用
A
的val()
而不是B
的val()
的原因是val()
方法具有private
访问修饰符,因此不能被覆盖。 Change the access modifier to protected
.将访问修饰符更改为
protected
。
public class A {
protected boolean val(){
return true;
}
protected boolean test() {
return val();
}
}
public class B extends A {
protected boolean val() {
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.