[英]How does method overriding work?
Look at the following code snippet: 查看以下代码片段:
class A
{
void fun1()
{
System.out.println("fun1 of A");
fun2();
}
void fun2()
{
System.out.println("fun2 of A");
}
}
class B extends A
{
void fun2()
{
System.out.println("fun2 of B");
}
}
in main method: 在主要方法中:
A a=new B();
a.fun1()
The output is: 输出为:
fun1 of A
fun2 of B
Can you please explain this output. 能否请您解释一下此输出。
According to me a.fun1
is calling fun1
of A
since fun1
is not overriden by B
(otherwise it would have called fun1
of B
). 根据我的说法, a.fun1
正在调用A
fun1
,因为fun1
没有被B
覆盖(否则它将调用B
fun1
)。 And, fun2()
in fun1
of A
is calling fun2
of B
since fun2
is overriden and object of B is created at runtime. 而且, A
fun1
的fun2()
调用了B
fun2
,因为fun2
被覆盖并且B的对象在运行时创建。 Am I thinking in correct direction ? 我在想正确的方向吗?
It has been answered but I'm putting this as an answer anyway because I object to the simplification of the example code and I can't properly express that in a comment. 它已经得到了回答,但是无论如何我都将其作为答案,因为我反对简化示例代码,并且无法在注释中正确表达出来。 Using names such as A and B and fun() really does not help anyone understand anything, including yourself. 使用诸如A,B和fun()之类的名称实际上并不能帮助任何人理解任何东西,包括您自己。 Try this: 尝试这个:
class Animal {
public void makeSound(){
System.out.println("<silence>");
}
}
class Cow extends Animal {
public void makeSound(){
System.out.println("Moooooooo");
}
}
public class Test {
public static void main(String[] args){
Animal animal = new Cow();
animal.makeSound(); // what sound is the animal going to make?
}
}
If you use something "realistic" that is easy to envision, it all of a sudden becomes almost self-explanatory. 如果您使用容易想到的“现实”东西,突然之间几乎可以不言自明。
Note: I purposely left out any reference to the abstract keyword because that is not within the context of this question. 注意:我故意省略了对abstract关键字的任何引用,因为这不在此问题的上下文内。
Your understanding is mostly correct. 您的理解基本上是正确的。 Just remember that all functions in Java are virtual and methods will be called depending on run-time type of the object you're working with. 只需记住,Java中的所有函数都是虚函数,并且将根据所使用对象的运行时类型来调用方法。 The trick is that when you do fun2();
诀窍是当您执行fun2();
there is an implicit this
so it becomes this.fun2()
. 存在一个隐式this
因此它变成this.fun2()
。 Since this in your exapmle this
points to an object of class B
, the overriden method will be called. 由于这在您的exapmle this
点类的对象B
,则覆盖方法将被调用。
Yes. 是。 Not much more to say than that your interpretation is correct. 只能说您的解释是正确的。
A a=new B();
That line says that get the implementations in the type B
when they called. 该行说在调用时以B
类型获得实现。 Keep it simple. 把事情简单化。 You are right. 你是对的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.