![](/img/trans.png)
[英]Why does the subclass in this Java code have a default constructor if the super-class does not have one?
[英]In java you're able to store objects of a subclass as a super-class type, why would you do this?
當您可以使用子類時,為什么要將“事物”對象聲明為超類,這將使您可以訪問所有相同的方法和字段,並且不需要對 B 類中的方法進行類型轉換。
public class A{}
public class B extends A{}
public class main()
{
A thing = new B();
}
這稱為多態性。 如果您有另一個名為C extends A
類,您可以創建一個List<A>
並將B
和C
放在那里。 然后你可以迭代它們並調用通用方法等。
也許是因為你想同時feed()
幾個Animal
,而不關心真正的Animal
類型:
interface Animal { void feed();}
class Dog implements Animal { public void feed() { /* feed a dog (give it a cat) */ }}
class Cat implements Animal { public void feed() { /* feed a cat (give it a bird) */ }}
class Cow implements Animal { public void feed() { /* feed a cow (give it some grass) */ }}
// Now I have some animals mixed somewhere (note that I am allowed to have the array declaring a supertype (Animal), and it can contain many kind of different animals)
Animal[] manyAnimals = new Animal[]{ new Dog(), new Cat(), new Cow() };
// I can feed them all without knowing really what kind of Animal they are. I just know they are all Animal, and they will all provide a feed() method.
for(Animal some : manyAnimals) { some.feed(); }
它是多態性。
這個例子可能會幫助你理解它。
在公司中,既有固定員工也有合同員工。 不同類型員工的工資計算方式不同。 但是 PF 計算對於這兩種類型的員工都很常見。 因此,在這種情況下,您可以在超類(Employee)中編寫通用代碼,而在子類(PermanentEmployee 和 ContractEmployee)中僅編寫自定義代碼。 通過這種方式,您可以使代碼可重用,而不是一次又一次地編寫,並且您還可以實現動態多態性。 大多數情況下,員工的類型是在運行時決定的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.