Polymorphism in Java

 

What is Polymorphism in java?

Polymorphism is one of the OOPs features, it allows us to perform a single action in different ways.

Polymorphism word comes from 2 Greek words poly and morphs, Poly means many and morphs means forms. That’s why can say polymorphism means many forms.

 

public class Employee{
   public void test(){
      System.out.println("Animal is making a sound");   
   }
}


public class Office extends Employee{
    @Override
    public void going(){
        System.out.println("Going to Office");
    }
}

public class Market extends Employee {
	@Override
	public void going() {
		System.out.println("Gogin to Market");
	}
}

 

In the above example with the same method name, we are performing different actions. As you can see that although we had the same action for all subclasses going() but there were different ways to do the same action.

 

This is a perfect example of polymorphism (a feature that allows us to perform a single action in different ways. It would not make any sense to just call the generic going() method as each Employee has a different going different location.

 

Types of polymorphism in Java.

There are two types of polymorphism in Java.

  • Compile-time polymorphism
  • Runtime polymorphism

 

Compile-time polymorphism.

It is also known as static polymorphism, we can achieve it using method overloading

If a class has multiple methods with having the same name but parameters are different or parameters type are different, it is known as Method Overloading.

 

we can overload the method in two ways

  • By changing the number of arguments
  • By changing the data type

 

Note: Method Overloading is not possible by changing the return type of the method only in Java.

 

Method Overloading Example: By using different types of arguments

// Java program for Method overloading 
  
package practice.Number;

class AdditionExample {

	// Method with 2 parameter
	static int add(int a, int b) {
		return a + b;
	}

	// Method with the same name but 2 double parameter
	static double add(double a, double b) {
		return a + b;
	}
}

package practice.Number;

class Addition {
	public static void main(String[] args) {
		System.out.println(AdditionExample.add(5, 10));

		System.out.println(AdditionExample.add(5.5, 10.5));
	}
}

Output:

15
16.0

 

In the above example, we are calling two add() method with different types of arguments, first calling with two int types of arguments, and in second method we are calling with two double types of arguments with the same add() method.

we notice that we are calling two methods with same name (add) but and the same number of arguments but the data types of arguments are different.

 

Method Overloading Example: By using different numbers of arguments.

 

// Java program for Method overloading 
package practice.Number;

class AdditionExample {

	// Method with 2 parameter
	static int add(int a, int b) {
		return a + b;
	}

	// Method with the same name but 3 parameter
	static int add(int a, int b, int c) {
		return a + b + c;
	}
}

package practice.Number;

class Addition {
	public static void main(String[] args) {
		System.out.println(AdditionExample.add(5, 10));

		System.out.println(AdditionExample.add(5, 10, 20));
	}
}

Output:

15
35

 

In the above example, we are calling two add() method with the same type of arguments but no arguments are different. In the first method, we called with two int types of arguments, and in the second method, we are calling with three int types of arguments with the same name add() method.

we notice that we are calling two methods with the same name(add) and the same type of arguments but a number of arguments are different.

 

Why Method Overloading is not possible by changing the return type of method only?

It is not possible because of ambiguity. When you are calling two methods with same name, same number of arguments and same type of arguments
and only the return type is different. than java not able determine to which method need to call that why we are getting ambiguity.

 

Let’s see how ambiguity may occur in programming:

 

class AdditionExample {

	// Method with 2 parameter
	static int add(int a, int b) {
		return a + b;
	}

	// Method with the same name but 2 parameter
	static double add(int a, int b) {
		return a + b;
	}
}

class Addition {
	public static void main(String[] args) {
		System.out.println(AdditionExample.add(5, 10));
	}
}

Output:

Compile Time Error: method add(int,int) is already defined in class AdditionExample

 

Can we overload java main() method?

Yes, we can overload main() method many times but JVM always looking for “public static void main(String[] args)” this full syntax with public static void main with string array as arguments only.

 

Let’s see how overload java main() method in programming:

 

package practice.Number;

class OverloadMain {
	public static void main() {
		System.out.println("main without args");
	}

	public static void main(String[] args) {
		System.out.println("main with String[] args");
	}

	public static void main(String args) {
		System.out.println("main with String args");
	}
}

Output:

main with String[] args

 

Runtime polymorphism

It is also known as Dynamic Method Dispatch, we can achieved it using method Overriding, If parent class and subClass (child class) has same method name, same argument type and same number of argument are declared. than that method is called Method Overloading.

 

What are the uses of Java Method Overriding?

It is used to provide the specific implementation of a method that is already provided by its ParentClass.
Method overriding is used for runtime polymorphism.

 

Example of without Method overriding:

//Creating a parent class.  
class Animal {
//defining a method  
	void run() {
		System.out.println("Animal is running");
	}
}

//Creating a child class class Dog extends Animal { //defining the same method as in the parent class public static void main(String args[]) { Dog obj = new Dog();// creating object obj.run();// calling method } }

Output:

Animal is running

 

In the above example if we are not the implementation of run() method in a subclass, and calling method through subclass object then it is automatically called the parent class run() method that why we need Method overriding.

 

Example of with Method overriding:

//Creating a parent class.  
class Animal {
//defining a method  
	void run() {
		System.out.println("Animal is running");
	}
}

//Creating a child class  
class Dog extends Animal {
//defining the same method as in the parent class
	void run() {
		System.out.println("Dog is running");
	}

	public static void main(String args[]) {
		Dog obj = new Dog();// creating object
		obj.run();// calling method
	}
}

Output:

Dog is running

 

In the above example if we are the implementation of run() method in both class subclass and parent. when we are calling run() method through subclass object then it is called the subclass class method implementation this is called Method overriding.

 

Hope this was helpful for you. If you have any questions please feel free to leave a comment. Thank you for reading.

10 Replies to “Polymorphism in Java”

  1. I needed to draft you one little bit of observation so as to say thank you once again just for the pleasant solutions you have featured in this case. It was really shockingly open-handed with you to grant publicly just what many of us might have offered for an ebook to get some dough for themselves, mostly now that you might have tried it in case you desired. These secrets as well served to be the good way to fully grasp that other people online have the identical interest much like my personal own to learn more regarding this matter. I am sure there are numerous more pleasant periods in the future for many who read your site.

  2. My husband and i felt absolutely ecstatic Edward could complete his inquiry from the ideas he discovered from your very own site. It’s not at all simplistic just to be giving for free helpful tips that men and women could have been making money from. And we do know we have the blog owner to appreciate because of that. Most of the explanations you’ve made, the easy blog menu, the friendships you assist to engender – it’s everything excellent, and it’s assisting our son and our family do think that content is cool, and that’s extremely fundamental. Many thanks for all the pieces!

  3. I simply wanted to thank you very much once more. I do not know what I would have tried without these techniques shared by you regarding that subject matter. It was actually an absolute scary scenario in my position, nevertheless taking note of this specialized tactic you solved the issue took me to weep with happiness. Now i’m thankful for your support and thus sincerely hope you really know what an amazing job you have been putting in training the mediocre ones via your webpage. Most probably you haven’t met any of us.

  4. My spouse and i got really joyous that Jordan managed to do his reports through your precious recommendations he had through the web pages. It is now and again perplexing to just find yourself handing out secrets and techniques which people may have been selling. So we keep in mind we have got the writer to give thanks to for that. The most important illustrations you have made, the simple web site navigation, the relationships you will help to foster – it’s got many overwhelming, and it’s really leading our son in addition to the family know that the situation is exciting, which is rather mandatory. Thank you for everything!

  5. I am glad for writing to make you know what a nice encounter my wife’s girl had studying your web site. She mastered several pieces, which include what it’s like to possess an awesome helping nature to let other individuals very easily know precisely some problematic subject matter. You truly exceeded people’s expectations. Thank you for presenting these practical, trusted, informative and in addition fun tips about this topic to Kate.

  6. I precisely desired to say thanks again. I’m not certain the things I could possibly have accomplished in the absence of the aspects contributed by you about my area. Completely was a alarming case for me, but being able to see a expert approach you dealt with it forced me to cry for contentment. Extremely grateful for the advice and believe you are aware of a powerful job that you’re accomplishing educating many others all through a blog. I’m certain you’ve never come across all of us.

Leave a Reply

Your email address will not be published.