• Post Reply Bookmark Topic Watch Topic
  • New Topic

polymorphism  RSS feed

 
rahul arno
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

what is advantage of using reference of super class in sub class object???
any one explain me that.
for eg. Animals obj = new Pets();
here Animals is super class and Pets is sub class which extends Animals.
can we use it reverse manner also???
like Pets obj1 =new Animals();
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch. The question you ask has been asked many times before; if you search in the forums, you'll most likely find useful answers.

See for example What is the reason for declaring your collections as superclass objects? which is about the same subject as your question.

rahul arno wrote:can we use it reverse manner also???
like Pets obj1 =new Animals();

No, you can't, because not all animals are pets.

Suppose we have class Pets extends class Animals, and another class Wildlife extends Animals. If it would be allowed to assign an instance of Animals to Pets, you could do this:
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!