Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regarding polymorphic bevaviour

Polymorphisim in Java stands for many forms what can be achieved by overriding sub-class method. Regarding generics which allows to pass in generic values, such as ArrayList<Object>. Is that part of polymorphism concept? Cheers

like image 751
uml Avatar asked Jan 15 '23 17:01

uml


1 Answers

Generics and Polymorphism are two different things.

Generics are used primarily to specify which type is expected. You can use wildcards to define a range of types. E.g. <? extends List> could apply to any type of List (LinkedList, ArrayList)

Polymorphism is the concept that an object can have many types. So an object can be an instance of List and an instance of ArrayList as an example.

For example, imagine three classes

public class Animal

public class Dog extends Animal

public class Cat extends Animal

If you have an instance of Dog, that object is both a Dog AND an Animal.

Obviously the two fit together quite nicely as if you define an ArrayList<Object> then you can add any Object to that list (Which is any class in Java)

like image 161
cowls Avatar answered Jan 20 '23 04:01

cowls