java类的多态,Java中的多态并从这些类创建对象

I'm a little confused exactly about how polymorphism and extending classes etc... works in Java when creating objects from these classes.

I recently had a problem which someone on here helped me resolved (see Not able to access object sub class's variable? (Java / Android)) for background.

I was attempting to create an object like so:

Quad hero = new Hero();

Where Hero was a subclass of Quad();

I had variables in my Hero class which I wasn't above to access.

The solution was to change my object creation to:

Hero hero = new Hero();

doing this, through my hero object, I was able to access all methods and variables in both my Quad and Hero classes.

My question now is - Why is this?

And with this in mind, when would it be useful to use my original method:

Quad hero = new Hero();

That one makes sense to me as Hero is also a quad. I've seen this type of declaration many times in Java code examples, and thought I understood, it but recent events have proved otherwise.

Would be grateful if someone could explain this for me - thanks

解决方案

Assume OtherHero is also a subclass from Quad with different behaviour:

This will work fine:

Quad hero = new Hero();

// some code

hero = new OtherHero();

Whereas the following won't compile:

Hero hero = new Hero();

// some code

hero = new OtherHero();

This doesn't seem to be useful. Now assume you have a method, that has Quad as return type. I'll write it in pseudocode:

Quad method() {

if (condition)

return new Hero();

else

return new OtherHero();

}

So you actually don't know if it will return a Hero or an OtherHero

Now, you can write:

Quad foo = method();

Now, you actually don't know the exact type of foo, but you can use it as Quad.

A popular example is java.util.List

You can write:

List list = Arrays.asList(1,2,3,4,5,6);

Collections.shuffle(list);

List is an interface, implemented by ArrayList, LinkedList and many other classes. Without knowing the code, we don't know which class exactly is returned by Arrays.asList(), but we can use it as a List.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值