Java Program to test polymorphism

Here is a Java program that helps you to understand the concepts of polymorphism. This program also tells us how to implement polymorphism correctly in Java programs. Here, we have also shown a common mistake and discussed how to avoid it.

polymorphism in a Java program – how to overload a method correctly?

class TestPolyMorph
{
int i=5,j=6;

void getSq(int i) //return type void
{
System.out.println(“result is “+i*i);

}

/* the next few commented lines won’t get compiled if the comments are removed. do you know why? These won’t get compiled, because, for polymorphism in java, the parameter list needs to be different. And, differing the return type only, as done in the commented method below is not polymorphism.*/
/*int getSq (int j)
{
System.out.println(“Hi”);
return j*j;
}*/

//first version of getSum(), we will overload this (polymorphism)

void getSum(int i, float f)
{ }

/*in the next version of getSum() method, a different set of parameters is used due to sequence interchange=>polymorph or method overloading done corectly*/

void getSum(float f, int i)

{ }
}

class Test1
{
public static void main(String args[])
{
TestPolyMorph t1= new TestPolyMorph();
t1.getSq(5);
}
}

Java program with method overloading (polymorphism) – 2nd program

class TestPolyMorph2
{
int i=5,j=6;

void getSq(int i)
{
System.out.println(“Hi from 1st method”);
System.out.println(“result is “+i*i);
}

/*the next getSq() shows polymorphism in java, the parameter list is different,
note that differing the return type only is not polymorph*/

int getSq ()
{
System.out.println(“Hi from 2nd method”);
return j*j;

}

/* next getSq() wont compile, even if it has different return type, as it has same param list as the getSq() above, it wont get compiled. that’s why kept commented*/

/*float getSq()
{
return 1;
}*/
}//end of class TestPolyMorph2

class Test2
{
public static void main(String args[])
{

TestPolyMorph2 t= new TestPolyMorph2();
t.getSq(8);
System.out.println(t.getSq());

}

}

Java Program to test polymorphism
Scroll to top
error: physicsTeacher.in