java - Polymorphism vs Inheritance -
suppose have 2 classes: animal , dog. dog subclass of animal. following code:
animal = new dog();
now can call methods of dog class through variable.
but question this: if can call of animal's methods through dog objects (inheritance) why should use polymorphism principle? can declare:
dog d = new dog();
with declaration can use of animal's methods , dog methods. why use polymorphism? thank answer.
in java, concepts of polymorphism , inheritance "welded together"; in general, not have way:
- polymorphism lets call methods of class without knowing exact type of class
- inheritance lets derived classes share interfaces , code of base classes
there languages inheritance decoupled polymorphism:
- in c++ can inherit class without producing polymorphic behavior (i.e. not mark functions in base class
virtual
) - in objective c can implement method on unrelated class, , call place knows signature of method.
going java, reason use polymorphism decoupling code details of implementation of counter-parties: example, if can write method feed(animal animal)
works sorts of animals, method remain applicable when add more subclasses or implementations of animal
. in contrast feed(dog dog)
method, tightly coupled dogs.
as far the
dog d = new dog();
declaration goes, there no general reason avoid if know rest of method deals dogs. however, in many cases later not case: example, class or methods insensitive exact implementation, example
list<integer> numbers = new arraylist<integer>();
in cases that, can replace new arraylist<integer>()
new linkedlist<integer>()
, , know code going compile. in contrast, had numbers
list been declared arraylist<integer> numbers
, such switchover may not have been certainty.
this called "programming interface". there answer on stack overflow explaining it.
Comments
Post a Comment