How to achieve Runtime polymorphism

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/08/achieve-runtime-polymorphism/

The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.

C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.

Consider the following example where a base class has been derived by other two classes:

 

abstract class Figure
{
	int dim1, dim2;
	Figure(int x, int y)
	{
		dim1 = x;
		dim2 = y;
	}
	abstract void area();
}
class Triangle extends Figure
{
	Triangle(int x, int y)
	{
		super(x,y);
	}
	void area()
	{
		System.out.println("Area of triangle is: "+(dim1*dim2)/2);
	}
}
class Rectangle extends Figure
{
	Rectangle(int x, int y)
	{
		super(x,y);
	}
	void area()
	{
		System.out.println("Area of rectangle is: "+(dim1*dim2));
	}
}
class RuntimePoly
{
	public static void main(String args[])
	{
		Figure f;
		Triangle t = new Triangle(20,30);
		Rectangle r = new Rectangle(20,30);
		f = t;
		f.area();
		f = r;
		f.area();
	}
}

Output for the above program isĀ as follows:

Area of triangle is: 300
Area of rectangle is: 600

Take your time to comment on this article.

Follow by Email
Facebook0
Facebook
Google+
https://codingsec.net/2016/08/achieve-runtime-polymorphism/

Add a Comment

Your email address will not be published. Required fields are marked *

Like the article? please consider sharing it. Thank you

Advertisment ad adsense adlogger