简体   繁体   中英

In java you're able to store objects of a subclass as a super-class type, why would you do this?

Why would you declare the "thing" object as the super-class when you can use the subclass, which would give you access to all of the same methods and fields and wouldn't require type casting for methods in the B class.

public class A{}
public class B extends A{}

public class main()
{
  A thing = new B();
}

This is called Polymorphism. If you had another class called C extends A you could create a List<A> and put both B and C there. Then you could iterate over them and call the common method etc.

Maybe because you want to feed() several Animal s at same time, without caring about the real type of 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(); }

It is polymorphism.

This example might help you understand it.

In a company there are both Permanent and Contract employees are there. The salary calculations happen differently for different type of employee. But PF calculation is common for both type of employees. So in this case you can write common code in super class(Employee) and only custom code in sub class(PermanentEmployee and ContractEmployee). This way you can make code reusable instead of writing again and again and also you can achieve dynamic polymorphism. Most of the time the type of employee is decided at run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM