本文介绍了使用超类初始化子类对象java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SuperClass object = new SubClass();
为什么要使用超类来实例化上面的子类对象?因为我学习实例化对象的唯一方法是:
Why use a superclass to instantiate a subclass object like above? Because the only way i learnt to instantiate an object is to:
SubClass object = new SubClass();
我正在学习java。
推荐答案
您可能有一个方法只接受 SuperClass
的实例。由于 SubClass
是 SuperClass
,您可以使用 SubClass 并将其视为 SuperClass
。
You may have a method that only takes an instance of SuperClass
. Since SubClass
is a SuperClass
, you can use an instance of SubClass
and treat it as SuperClass
.
工作时使用相同的行为带接口:
The same behavior is used when working with interfaces:
List someList = new ArrayList();
这就是多态的美。它允许您在不破坏代码的其余部分的情况下更改类内部的实现。
That's the beauty of polymorphism. It allows you to change out the implementation of the class' internals without breaking the rest of your code.
这篇关于使用超类初始化子类对象java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!