In the question,I learned that the polymorphism has 4 types:
Coercion,
Overloading
Parametric Polymorphism
Inclusion
So I did not completely understand what does mean by Inclusion, I need same example to implement this notion.
In the question,I learned that the polymorphism has 4 types:
Coercion,
Overloading
Parametric Polymorphism
Inclusion
So I did not completely understand what does mean by Inclusion, I need same example to implement this notion.
As already suggested, search a little bit yourself to get a deeper idea of this topic... Here is one possible explanation:
[...] subtyping allows a function to be written to take an object of a certain type T, but also work correctly, if passed an object that belongs to a type S that is a subtype of T (according to the Liskov substitution principle) Wikipedia - Polymorphism
abstract class Vehicle
{
abstract void move();
}
class Car extends Vehicle
{
public void move() { ... }
}
class Ship extends Vehicle
{
public void move() { ... }
}
public void moveVehicle(Vehicle v)
{
v.move();
}
Here is an example for inclusion polymorphism:
Vehicle [] vs = new Vehicle [2];
vs[0] = new Car();
vs[1] = new Ship();
for(Vehicle v : vs)
{
moveVehicle(v);
}
Or another example:
Car c = new Car();
Ship s = new Ship();
moveVehicle(c);
moveVehicle(s);
For additional information see the Wikipedia - Polymorphism page... But still search yourself for this topic to get a deeper idea of it!
The inclusion polymorphism means that you can instantiate an object from his super class. For example you have
public class Person {
.
.
}
public class Employee extends Person{
.
.
}
So you can create an object
Person x = new Employee();
This is useful for example if you need to create a lot of different object that refere to a single superType
For example you have SuperTyper geometric_figure and SubTyper figure (circle, square, triangule,..). The geometric_figure may have two attributes x,y for the screen location and an abstract method "draw",to draw on screen, that each figure ,that extend it , need to implement
Thanks to dynamic link
of java when you call geometricFigure.draw(), it will automatically know what type of geometric_figure you are calling (circle, square, triangule,..), and invoce this draw method
To manually check what is his specific class you can do:
Geometric Figure x = new Square();
if(x instance of Square){...}
A popular case is when you want to refere to a generic object like this
Object x = new AnyClass();
because the Object is the generic super class that every class have. (When you do not extend anythig, by default it extand Object)