6 java oop polymorphism overriding
我有以下课程:
class foo {
public void a() {
print("a");
}
public void b() {
a();
}
}
class bar extends foo {
public void a() {
print("overwritten a");
}
}
Run Code Online (Sandbox Code Playgroud)
当我现在调用bar.b()时,我希望它在foo中调用重写的方法a().但是,它会打印"a".
Mik*_*ike 10
你的两个班级是不同的包吗?你的foo类方法是公共的,受保护的,私有的还是包本地的?显然,如果它们是私有的,这将不起作用.也许不那么明显,如果它们是本地包(即没有公共/受保护/私有范围),那么只有在与原始类位于同一包中时才能覆盖它们.
例如:
package original;
public class Foo {
void a() { System.out.println("A"); }
public void b() { a(); }
}
package another;
public class Bar extends original.Foo {
void a() { System.out.println("Overwritten A"); }
}
package another;
public class Program {
public static void main(String[] args) {
Bar bar = new Bar();
bar.b();
}
}
在这种情况下,你仍然会得到'A'.如果在Foo public或protected中声明原始的a()方法,您将获得预期的结果.
可能是您正在尝试使用静态方法,这些方法无法正常工作,因为它们不会被覆盖.
一个好的检查方法是将@Override注释添加到bar.a()并查看编译器是否给出了一个错误,即a()实际上没有覆盖任何东西
当我运行以下内容时:
public class Program {
public static void main(String[] args) {
bar b = new bar();
b.b();
}
}
class foo {
public void a() {
System.out.printf("a");
}
public void b() {
a();
}
}
class bar extends foo {
public void a() {
System.out.printf("overwritten a");
}
}
Run Code Online (Sandbox Code Playgroud)
我得到以下输出:
overwritten a
Run Code Online (Sandbox Code Playgroud)
这是我期望看到的.