Java 多态性使用其超类变量创建子类对象
所以我是一名学生,正在学习 Java.有一个概念我很难理解,我希望有人可以为我阐明这一点.我的问题是关于多态性.例如,假设我有以下代码.
So I am a student and in the process of learning Java. There is one concept that I am having a difficult time grasping and am hoping that someone could shed some light on this for me. My question is regarding polymorphism. Let's say for example I have the following code.
Animal a = new Lizard("Lizzy", 6); //Lizard extends Animal
据我了解,由于变量类型是Animal,a将具有Animal的所有特征.但是,由于创建的对象是 Lizard,因此将使用 Lizard 类中的任何重写方法,而不是 Animal 类中的方法.这是正确的>
From what I understand, since the variable type is Animal, a will have all the characteristics of an Animal. But, since the object created is a Lizard, any overridden methods in the Lizard class will be used instead of those in the Animal class. Is this correct>
另外,创建一个类的时候会用到哪些类的构造函数?
Also, which classes constructor will be used while creating a?
感谢您的帮助.我看起来很不错
Thanks for any help. I have looked quite
推荐答案
1.据我了解,由于变量类型是Animal,a将具有Animal的所有特征.但是,由于对象created 是一个 Lizard,任何在 Lizard 类中被覆盖的方法都会用于代替 Animal 类中的那些.这是正确的>
1.From what I understand, since the variable type is Animal, a will have all the characteristics of an Animal. But, since the object created is a Lizard, any overridden methods in the Lizard class will be used instead of those in the Animal class. Is this correct>
是的,你是对的.
2.另外,创建类的时候会用到哪些类的构造函数?
2.Also, which classes constructor will be used while creating a?
Animal a = new Lizard("Lizzy", 6); //Lizard extends Animal
因为,Lizard 是 Animal 的子类,首先,将调用 Lizards 构造函数,然后从 Lizards 构造函数调用 Animal 构造函数,因为 Lizard 构造函数的第一行是super() 默认情况下,除非您使用 this() 调用 Lizard 的重载构造函数.在 Animal 构造函数中,第一行会再次调用 super().假设 Animal 没有扩展任何类,java.lang.Object 的
构造函数将被调用,因为 java.lang.Object
是每个对象的超类.
As, Lizard is a subclass of Animal, First, Lizards constructor will be invoked, then from Lizards constructor, there will be a call to Animal constructor as the first line in your Lizard constructor would be super() by default unless you call an overloaded constructor of Lizard using this(). In Animal constructor there will be another call to super() in the first line. assuming Animal doesn't extend any class, java.lang.Object's
constructor will be invoked as java.lang.Object
is the super class of every object.
public Object() {
}
Class Animal {
public Animal(){
//there will be a super call here like super()
}
class lizard extends Animal {
public Lizard(your args) {
//there will be a super() call here and this call's animal's no-args constructor
}
}
}
执行顺序为
- 将调用 Lizards 构造函数
- 除非 this() 调用重载构造函数,否则调用 super() 即调用的 Animals no-args 构造函数
- java.lang.Object 的构造函数将使用 super() 从 animal 中调用
- java.lang.Object 的构造函数代码将执行
- 将执行动物构造函数代码
- 将执行 Lizards 构造函数代码
相关文章