问题描述
当从这些类创建对象时,我对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();
其中Hero是Quad()的子类;
Where Hero was a subclass of Quad();
我的Hero类中有我无法访问的变量.
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();
通过我的hero对象,我可以访问Quad和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();
这对我来说很有意义,因为Hero也是四边形.我已经在Java代码示例中多次看到这种类型的声明,并且以为我理解了,但是最近的事件证明不是这样.
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
推荐答案
假定OtherHero
也是Quad
的子类,具有不同的行为:
Assume OtherHero
is also a subclass from Quad
with different behaviour:
这可以正常工作:
Quad hero = new Hero();
// some code
hero = new OtherHero();
以下内容无法编译:
Hero hero = new Hero();
// some code
hero = new OtherHero();
这似乎没有用.现在假设您有一个方法,其返回类型为Quad
.我将用伪代码编写它:
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();
}
所以您实际上不知道它将返回Hero
还是OtherHero
So you actually don't know if it will return a Hero
or an OtherHero
现在,您可以编写:
Quad foo = method();
现在,您实际上不知道foo
的确切类型,但是可以将其用作Quad
.
Now, you actually don't know the exact type of foo
, but you can use it as Quad
.
一个流行的例子是java.util.List
您可以写:
List<Integer> list = Arrays.asList(1,2,3,4,5,6);
Collections.shuffle(list);
List
是一个接口,由ArrayList
,LinkedList
和许多其他类实现.在不知道代码的情况下,我们不知道Arrays.asList()
确切地返回了哪个类,但是我们可以将其用作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
.
这篇关于Java中的多态性并根据这些类创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!