开发者

Use of base class object by child class reference - java

What开发者_如何学Python is the use of creating base class object using child class reference in Java


If I understand correctly, you mean:

class Parent {
   ...
}

class Child extends Parent {
   ...
}

Parent p = new Child ();

There are many reasons:

  1. Flexibility: you can use Parent as a parameter type, and pass any subclass (i.e. Child and other) as this parameter.

  2. Polymorphism: You can override Parent method in several Child classes and use them in turn where Parent object required (like in Strategy pattern)

  3. If you're working on some public API you can make Parent class public and visible to everyone but all Childs can be invisible to outer users. It can make your API more narrow. Good example is Collections API. There are 32 implementations (i.e. Childs) which are used implicitely, but only a few public interfaces. You can obtain synchronized, unmodifiable and other collections through Collection (i.e. Parent) interface not knowing implementation details.


Animal myAnimal1 = new Dog();
Animal myAnimal2 = new Cat();
Animal myAnimal3 = new Horse();

Suppose Animal has a method called getAnimalSound() and Dog, Cat, Horse all override that method according to them. Now, this code is very extensible, your API can have just one method getAnimalSound() to indicate sound of any kind of an animal, in tern each animal class has already implemented their own version of getAnimalSound()

System.out.println(getAnimalSound(myAnimal1)); //runtime finds animal1 is dog, prints Bark
System.out.println(getAnimalSound(myAnimal2));//runtime finds animal2 is cat, prints Meow
System.out.println(getAnimalSound(myAnimal3));//runtime finds animal3 is horse, prints Niih

As you can see one Method getAnimalSound() is the standard API, but we achieved so much of extensibility.


If you mean things like

List<String> list = new ArrayList<String>()

then you are not actually creating an instance of the superclass. You are only telling the user to handle it as if it was one. The point is that you often don't need to know the exact implementation that was chosen and wish to retain the ability to change the implementation. Hence you only tell a user of an API that something is a List and if your algorithm requires it, you can change the implementation to use a LinkedList instead, without changing the API.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜