I wonder why it is allowed to have different type of object reference? For example;
Animal cow = new Cow();
Can you please give an example where it is useful to use different type of object reference?
Edit:Cow extends Animal
I wonder why it is allowed to have different type of object reference? For example;
Animal cow = new Cow();
Can you please give an example where it is useful to use different type of object reference?
Edit:Cow extends Animal
This is basically a concept of standardization.
We know that each animal have some common features. Let us take an example of eating and sleeping, but each animal can have different way of eating or sleeping ... then we can define
Now you do not have to define different objects to different classes... just use Animal and call generally
This is called polymorphism and it's one of the most powerful aspects of Java.
Polymorphism allows you to treat different objects the same.
It's a great way to create re-usable, flexible code.
Unfortunately it's a part of Java that new programmers often take awhile to understand.
The example you've provided involves inheritance (extending a class).
Another way to enjoy the benefits of polymorphism is to use interfaces.
Different classes that implement the same interface can be treated the same:
Simply putting all
Cows
areAnimals
. So JAVA understands that whenCow extends Animal
, a Cow can also be called as Animal.This is Polymorphism as others have pointed out. You can extend
Animal
withDog
and say that Dog is also an Animal.On a simpler note, this enables polymorphism. For example you can have several objects that derive from Animal and all are handle similar.
You could have something like:
The Feed() method must then be overriden within each child class.
By the way, code is C#-like but concept is the same in Java.
This is at the heart of polymorphism and abstraction. For example, it means that I can write:
... and handle any kind of input stream, whether that's from a file, network, in-memory etc. Or likewise, if you've got a
List<String>
, you can ask for element 0 of it regardless of the implementation, etc.The ability to treat an instance of a subclass as an instance of a superclass is called Liskov's Substitution Principle. It allows for loose coupling and code reuse.
Also read the Polymorphism part of the Java tutorial for more information.
In another class/method you might want to use different implementations of the same interface. Following your example, you might have something like:
Now you can implement the details in your animal classes and don't have to extend this method anytime you add a new animal to your programm.
So in some cases you need the common interface in order not to implement a method for each implementation, whereas on other occasions, you will need to use the explicit implementation.