Java 中的重写规则
这里有两个例子:
public class A {
public void foo(A a) {
System.out.println("in A");
}
}
public class B extends A {
public void foo(B b) { // (1)
System.out.println("in B");
}
public void f(Object o) { // (2)
System.out.println("in B");
}
}
我不明白为什么 (1) 和 (2) 被认为是 A 的 foo()
的重写方法。方法 1 接受比原始 foo()
更低的类,我的意思是我不能向她发送任何 A 类。据我所知,(1) 不扩展 foo ()
,但它仍然算作覆盖 - 为什么?(与(2)类似,但相反)。
我让我认为它被覆盖的原因是这样的:
当我尝试运行时
B b = new B();
b.foo(b);
,它会检查 A
是否有一个接受 B
的 foo
代码>.因为每个 B
都是一个 A
,所以它确实有一个,所以它应该打印“in A”而不是“in B”,因为 B 不会覆盖它。但它打印“in B”..
Here are two examples:
public class A {
public void foo(A a) {
System.out.println("in A");
}
}
public class B extends A {
public void foo(B b) { // (1)
System.out.println("in B");
}
public void f(Object o) { // (2)
System.out.println("in B");
}
}
I don't understand how come (1) and (2) are considered to be an overrided method for A's foo()
. method number 1 accepts a lower class than the original foo()
, I mean that I can't send her any class of A. as I see it, (1) does not extend foo()
, but it is still counts as an override- why?( Similar argument for (2), but opposite).
The reason that I made me think that it is overrided is this:
when I'm trying to run
B b = new B();
b.foo(b);
It checks if A
has a foo
that accepts B
. since every B
is an A
, it does have one so it ought to print "in A" and not "in B" because B does not overrides it. but it prints "in B"..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它们都没有重写超类 A'a 方法。
当我编译上面的代码时,我收到错误:
但请注意,可以从重写方法返回子类。以下编译无错误。
Neither of them override the super class A'a method.
When I compile the above I get errors:
But note that it is ok to return a subclass from an overriding method. The following compiles without error.
为了让覆盖发挥作用,方法签名应该相同。在这种情况下,他们不是因为他们所采取的论点不同。它们只是成员函数,其中 1,2 是重载。 (考虑 2 是一个拼写错误。它应该是
foo
而不是f
)For overriding to work, method signatures should be the same. In this case, they aren't because they differ in the arguments they take. They are just member functions with 1,2 being overloads. ( Considering 2 as a typo. It should be
foo
instead off
)1) 和 2) 都不会覆盖任何内容,因为您可以通过添加 @Override 注释来验证这一点:
这两种方法都不会编译,因为它不会覆盖任何内容。
Neither 1) nor 2) override anything, as you can verify that by adding the @Override annotation:
Neither method will compile, since it doesn't override anything.