Site icon JavaGoal

Polymorphism in Java

Here is the table content of the article will we will cover this topic.
1. What is Polymorphism in JAVA?
2. Types of Polymorphism in Java?
3. Static polymorphism Or compile-time polymorphism
4. Dynamic polymorphism Or runtime polymorphism

5. When to use Polymorphism?
6. When to use static polymorphism real-time example?
7. When to use dynamic polymorphism?
8. Difference between overloading and overriding

9. What is Method overloading in Java?
10. You can overload by changing the number of arguments/parameters?
11. You can overload by changing the data type of arguments?
12. The Order of the parameters of methods?

13. An important concept of method Overloading When to use Polymorphism?
14. Why ? we can’t overload by changing the return type of the method?
15.
Can we overload the static method in java?
16. Can we overload the main method in java?
17. What is Method overriding in Java?
18. What are the Rules of
 Method overriding in Java?
19. Can we override the final method in java?
20. Can we override the static method in java?
21. Covariant return type in java
22.
Method overriding in Exception handling?

Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word “poly” means many, and “morphs” means forms. So, Polymorphism means many forms.

Real-life example: You have a smartphone, and you can communicate with your friend. The communication mode you choose could be anything. You can do a call, a text message, mail, etc. So, there is a common goal which is communication, but their approach is different. Therefore, It is called Polymorphism.

Video available in Hindi

What is Polymorphism in JAVA?

Polymorphism is the OOPs feature that allows us to perform a single action in different ways. In JAVA, we can perform different tasks with a single action.

For example: Let’s say we have two cars both belonging to vehicles. All vehicles have some common properties. All Vehicles have their own speed, power, color, etc. Since this is a common thing in Vehicles, each vehicle behaves differently. So, we can take it generic (Common) class.

class Vehicles
{
    public void detailsOfVehicle()
    {
        System.out.println("This is generic class of vehicles");
    }
}

class Swift extends Vehicles
{
    @Override
    public void detailsOfVehicle()
    {
        System.out.println("Its top speed it 200km");
        System.out.println("Its power speed it 1200cc");
    }
}

class HondaCity extends Vehicles
{
    @Override
    public void detailsOfVehicle()
    {
        System.out.println("Its top speed it 300km");
        System.out.println("Its power speed it 1800cc");
    }
}

class MainClass
{
    public static void main(String arg[])
    {
        // Creating an object of Swift class call and assign
        // to reference variables of vehicles.
        Vehicles vehicles = new Swift();
        vehicles.detailsOfVehicle();

        // Creating an object of HondaCity call and assign
        // to reference variables of vehicles.
        vehicles = new HondaCity();
        vehicles.detailsOfVehicle();
    }
}

Output: Its top speed is 200km
Its power speed is 1200cc
It’s top speed is 300km
Its power speed is 1800cc

In the above example, we created three classes. One class is Vehicles that is holding common methods (generic features of Vehicles). Also, The other two classes are extending the Vehicles class and override the method detailsOfVehicle. Both classes, override the method according to the features.
As you can see, we have common action detailsOfVehicle() in the Vehicles class. The common action is overridden by all subclasses so that each class behaves differently. It is a perfect example of polymorphism because it performs a single action in different ways.

Types of Polymorphism in Java

  1. Static polymorphism / Compile-time polymorphism
  2. Dynamic polymorphism / Runtime polymorphism

1. Static polymorphism Or compile-time polymorphism

Static polymorphism resolve as a compile-time. Also, this Static Polymorphism can achieve by method overloading. First, You should read about method overloading and how many ways to overload a method. If you have read the method overloading, then you can read further.

At compile time, Java knows which method to invoke by checking the method signatures.

Class AdditionsOfNumber
{
	public void addition(int a, int b)
	{
		System.out.println("Addition of two numbers = "+ (a+b));
	}
	public void addition(int a, int b, int c)
	{
		System.out.println("Addition of three numbers = "+ (a+b+c));
	}	
}

class ExampleOfStaticPolymorpism
{
	public static void main(String arg[])
	{
		AdditionsOfNumber addNumbers = new AdditionsOfNumber();
		// calling the method have two parameters
		addNumbers.addition(2,3);
		// calling the method have three parameters
		addNumbers.addition(2, 4, 5);
	}
}

Output: Addition of two numbers = 5
Addition of three numbers = 11

2. Dynamic polymorphism Or runtime polymorphism

It’s a process resolved at runtime. Dynamic Polymorphism can achieve by method overriding. You should read about the method overriding and What are the rules to override a method. If you have read the method overloading, then you can read further.

Method overriding

If the parent class and child class have a method with the same signatures. Then it’s called method overriding. Let’s say a parent class has a method sum(int, int), and a child class provides the specific implementation of the method that has been declared in a parent class. Hence, It is known as method overriding.

Finally, For more details on method overloading, You can go through the link.

class Additions
{
	public void addition(int a, int b)
	{
		System.out.println("Method of Parent(Additions) class and Addition of two 
                numbers = "+ (a+b));
	}
}

class ExampleOfDynamicPolymorpism extends Additions
{
	// Override the method of parent class (Additions)
	public void addition(int a, int b)
	{
		System.out.println("Method of child(ExampleOfDynamicPolymorpism) class and 
                 Addition of two numbers = "+ (a+b));
	}
	
	public static void main(String arg[])
	{
		Additions addNumbers = new Additions();
		addNumbers.addition(2,3);
	}
}

Output: Method of Parent(Additions) class and Addition of two numbers = 5

Rules:

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. The method must have the same return type as in the parent class
  4. There must be an IS-A relationship (inheritance).

When to use Polymorphism?

We have read about polymorphism in previous topics. We have seen many things about static polymorphism and dynamic polymorphism. But the most important part is to know when to use polymorphism real time example? Now, we will discuss when to use static polymorphism and dynamic polymorphism.

1. When to use static polymorphism?
2. When to use dynamic polymorphism?

When to use static polymorphism real-time example?

First scenario 1:  We can overload a method when we want to perform different operations on the base of parameters. Let’s take the example of a String class.

public int indexOf(int ch)
public int indexOf(int ch, int fromIndex)

public indexOf(int characterName)This method accepts only one parameter. It returns the index value of the first occurrence of the specified character You can read this method in detail.

indexOf(int characterName, int fromIndex)This method accepts two parameters. One parameter is the name of a character and another is the index to start the search. It returns the index value of the first occurrence of the specified character. You can read this method in detail.

Now you have understood the reason for method overloading. Here both methods perform different functionality by the different numbers of parameters.

class ExampleOfIndexOf
{ 
       public static void main(String args[])
       { 
	String name = "JAVA WINGS"; 
	int index = name.indexOf('A');
        System.out.println("The index of first occurrence of given character is = "+index);
	
	int index1 = name.indexOf('A', 2);
	System.out.println("The index of character after the specified index for search = 
	"+index1); 
	}
}

Output: Output: The index of first occurrence of given character is = 1
The index of character after the specified index for search = 3

First scenario 2: Suppose we are working on an existing project that is already developed. As per the new requirement, we have to make some new changes to the existing method. To provide a new functionality we have to send one more parameter in the existing method.  As we have to maintain old functionality as well. In these types of situations, we should overload the method so that we will not break the existing code.

When to use dynamic polymorphism?

Method overriding is only possible in inheritance. When you want to provide specific implementation to an inherited method. Then you should use the method overriding.
You can provide the implementation of the method of the derived class without even modifying the parent class code.
According to the concept of polymorphism while writing the code we should use of generic interface instead of a concrete implementation. Because it provides an ease to add new implementations if the requirement arises in the future.

In Java, AbstractCollection class provides the generic interface for all the classes that extend it. AbstractCollection class has various method that is overridden by classes according to their use.
We will discuss the add(E e) method that is defined in the AbstractCollection class. But ArrayList and HashSet provide their body according to their use.

Difference between overloading and overriding

We have read the overloading in java and overriding in java. We have seen many examples with different scenarios. Now, we will see what is the difference between method overloading and method overriding or the difference between overloading and overriding. It is the most common question in interviews and most programmer gets confused to find the difference between method overloading and method overriding.

Video available in Hindi

Method Overloading

1.  Method overloading in java is possible within the class. Method overloading in Java means multiple methods having the same name but different parameters. A class can hold several methods having the same name, but different types/orders/number of parameters.

2. Method Overloading happens at compile-time. In method overloading the compiler binds the call at compile time.

3. In method overloading, it is possible to overload the Static methods.

4. In method overloading, it is possible to overload the final methods.



5. In method overloading, it is possible to overload the private methods.

6.  Method overloading is possible within the class. Because we can define any number of methods with the same name but different parameters.

7. You can’t overload the method based on the return type. The return type of the overloaded method does not matter. It can be the same or different.

Method Overriding

1. Method overriding in java is only possible with the concept of Inheritance. As you know by using of inheritance concept in Java, we can inherit the method of the parent class to the child classMethod overriding in Java is a feature through which we can define the method in the child class that is already defined in parent classes. If a method in a child class has the same name and parameters as a method defined in the parent class, then the method defined in the subclass is called an overriding method, and the method defined in the parent class is called an overridden method.

2. Method overriding happens at run-time. In the method overriding the compiler binds the call at run time.


3. In method overriding we can’t override the static methods. If we override the static method, it is considered method hiding.

4. In method overriding we can’t override the final methods.

5. In method overriding we can’t override the private methods. Because the private method is not inherited in the child class.

 6. Method override is not possible within the class. Method overriding is only possible by the use of inheritance.  

7. After Java 5, Java allows us to change the return type of the overriding method(Method in child class). But the return type of the overriding method (Method of child class) must be a subtype of the overridden method (Method of Parent class). 

Exit mobile version