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

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.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>

yes, you are Right.

2.Also, which classes constructor will be used while creating a?

Animal a = new Lizard("Lizzy", 6); //Lizard extends Animal

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

}

}

}

The order of execution would be

Lizards constructor will be invoked

unless there is a this() call to an overloaded constructor, a call to super() i.e., call's Animals no-args Constructor

java.lang.Object's Constructor will be invoked from animal using super()

java.lang.Object's constructor code will execute

Animals constructor code will execute

Lizards constructor code will execute

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值