Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why different types of object reference is allowed in Java?

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

like image 458
Salih Erikci Avatar asked Dec 01 '22 22:12

Salih Erikci


1 Answers

This is at the heart of polymorphism and abstraction. For example, it means that I can write:

public void handleData(InputStream input) {
    ...
}

... 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.

like image 83
Jon Skeet Avatar answered Dec 04 '22 12:12

Jon Skeet