简体   繁体   中英

Purpose of assigning objects of subclass to a superclass reference?

I have always this question burning in me. Why do people assign objects of subclass to a superclass reference as below:

What exactly are the benefits and reasons that makes people do so?

public static void main(String[] args)
{
    A obj1 = new C(); //Why do this ?
    C obj2 = new C(); //When we can simply do this ???
}

class A
{}

class B extends A
{}

class C extends B
{}

I understands all the logic where a Class Dog is an Animal but Animals are not essentially Dogs. I've also bumped into this link: Why assign a subclass object to a superclass reference? which asked similar question as me (but was marked as duplicate with a non-relevant link: What does it mean to "program to an interface"? )

In here: Why assign a subclass object to a superclass reference? Some vague answers were given as reason for doing so. Unfortunately no more detailed answers could be given before it was marked duplicated with an irrelevant link.

Hopefully someone could look into this question and give a detailed reply on the reason of assigning objects of subclass to a superclass reference.

Classic example. Store list of objects that can draw themselves and draw them when needed.

List<Drawable> toDraw = new ArrayList<Drawable>();
// Add objects to draw
toDraw.add(new Circle(0, 0, 10));
toDraw.add(new Rectangle(10, 10, 20, 20));

// draw them
for (Drawable drawable : toDraw) {
  // each object knows how to draw itself
  drawable.draw();
}

If tomorrow someone implement a new drawable (say triangle) this code will still work.

This code is also an example of Open-Close principle, that says that the code is Open for extension, but Closed for modification. You don't need to change code (modification) that draws all object, but you can still add new drawables (extension).

In a nutshell:

   Class Pet

   Class Dog extends Pet
   Class Cat extends Pet
   Class Mouse extends Pet

you could wrap your Pets in "one" list, by threading them as a pet:

 List<Dog> dogs = new LinkedList<Dog>();
 dogs.add(new Cat()) // error.

 List<Pet> pets= new LinkedList<Pet>();
 pets.add(new Cat());  //works
 pets.add(new Dog());  //works
 pets.add(new Mouse());  //works

Now, if somebody asks you for your pets, you only have ONE Pet list:

 for (Pet p : pets){
    System.out.println(p) //prints dog, mouse and cat.
 }

If you keep them at their most concrete type you would need to maintain 3 lists to track your pets.

Note, that a cat which is upcasted to a pet does not loose it's specific cat-attributes. They are just not available while seen as a pet - You can cast it down to a cat again to call cat.mew() or dog.bark() .

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