英文:
Using, if applicable, the subclass' method
问题
我有以下的代码:
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());
}
}
它返回 true,因为 A 中的 test() 方法调用了 A 的 val() 方法。经过一些研究,我理解这在 Java 中是预期的。然而,我希望当从 B 调用 test() 时打印出 false,并且当从 A 调用时打印出 true。
是否有可能实现这样的效果?
英文:
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?
答案1
得分: 2
你的代码调用 A 的 val() 而不是 B 的 val() 的原因是 val() 方法具有 private 访问修饰符,因此无法被覆盖。将访问修饰符更改为 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 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;
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论