使用时,如果适用,使用子类的方法。

huangapple go评论64阅读模式
英文:

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

你的代码调用 Aval() 而不是 Bval() 的原因是 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;
    }
}

huangapple
  • 本文由 发表于 2020年4月5日 19:00:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/61041528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定