Polymorphism in Java and how to use it


Polymorphism in Java, means that you can overload method to make it intuitive and usable. Learn Java polymorphism and where you can apply this concept.

Polymorphism is a word that defines that one thing, one element or one method in case of Java can take different forms while keeping its meaning or purpose of existence same. The purpose of giving the power of polymorphism to OOP and of course to Java. There are several needs which can compel you to use the polymorphism.

There is a very common example you will get in so many books and I think is a good one too. The draw method. Lets look at it in little more detail. If you want to create a program which is a drawing based program. So you need to draw either a line or a circle or eclipse or may be a rectangle or square. so instead of creating different method like drawRectangle(), drawCircle(), drawLine() or drawSquare() etc. but there could be a common method like draw() with just number of parameters different.

I am not programming that example because that may take you too long to get along with the concept understanding. So here is a smallest program you may want to understand the concept.


public class Polymorphism {
    public void method(int a){
    
    }
    
    public int method(){
        return 0;
    }
    
    public String method(String s, int i){
        return "";
    }
}

This is a simplest example of polymorphism. see, there are only three methods but all the with the same name. One thing to be noted is that, the method signature in the overloaded methods is by the number and type of parameter not by its return type. I suggest you to remember this as this will also help you in some interview.

Now I would also suggest you to create your own overloaded draw method, which will create the various drawings. As you might not be expert with Java yet so, just try printing on the console when the method is invoked. Now let us move on to see another example. The Constructors of the class can also be overloaded.

for example


public class Polymorphism{
	Polymorphism(){

	}

	Polymorphism(int a){

	}

	Polymorphism(int a, String s){

	}
}

so in this way you can also overload the class constructors. I Suggest this as an exercise you try to use this in any of your demo program.