Polymorphism in Java


What is Polymorphism?

Polymorphism is an important Object oriented concept and widely used in Java and other programming language.  Polymorphism in java is supported along with other concept like abstraction, encapsulation and inheritance. bit on historical side polymorphism word comes from ancient Greek where poly means many so polymorphic are something which can take many form. In this java polymorphism tutorial we will see what polymorphism in Java is, how polymorphism is implemented in Java, why should we use polymorphism and how can we take advantage of polymorphism while writing code in Java. Along the way we will also see a real world example of using polymorphism in Java


Types Of Polymorphism:


There are two types of polymorphism
1. Compile time polymorphism
2. Run time polymorphism




Overloaded Methods

Let's use our makeSound() example again. Let's say a dog makes a woof sound, but if the dog is injured, the dog might make a whimper noise instead. How can we use makeSound() to produce both sounds? Take a look at this code snippet: 
Example of overloaded method makeSound()

NOTE: At this point, if you're not sure you understand the code you see, you REALLY should go back to the Intermediate Tutorials and read the tutorial on Methods In Java. Then you can come back to learn about polymorphism in Java once you have a better understanding of methods.
We can see here that depending on the number of parameters we pass to makeSound(), the dog will make a different sound. But wait! Couldn't we have just used an if statement and make this just one method? Yes, we could have done that and that's probably a better way of programming this for this particular example. What if an outside action causes the difference in dog sound though? Something like this: 
Passing a parameter overloaded method

If the dog did not have the variable to know it was hurt, you would not be able to write that if statement as easily.
You can overload a method as much as you want as long as the number of parameters are different or the types of parameters are different. You could not do this for example: 
Duplicate overloaded methods

This is because those are the same number of parameters AND are the same types of parameters. 

Overridden Methods

In Java, you can create a method in a superclass (or parent class), then in a subclass ALSO define that method. Let's see an example of this using Animal: 
Superclass defines method
Subclasses define method to override or not

Now, let's say you could actually create Animals. If you could, then calling makeSound() would call the method defined in the superclass. If you create a specific Dog, calling makeSound() will display “woof”. Now let's say you created a specific Cat. In that example, Cat does not have a makeSound() method, so when you call makeSound() on Cat, it calls the method in the superclass Animal and does nothing. Remember, Cat and Dog are subclasses of Animal because they extend Animal.
This behavior is called method overriding, and it is EXTREMELY powerful stuff when it comes to polymorphism in Java. Java will let you do this because its possible more specific types of objects have more specific behaviors for actions. How does Java then know which method to actually call? Java will always pick the object's true type for choosing which method to call, the superclass or the subclass. We will see what true type really means in the next section. 

Dynamic Method Binding

Do not let the long name confuse you. This is not that scary of a term! We won't discuss why this is dynamic, but let's just say that Java decides what method to call during runtime, or once the program is running. Dynamic method binding is how Java decides what method to call when it has to decide between the superclass and the subclass. So, how exactly does it decide? To illustrate this point, we must first illustrate the concept of true type versus referenced type. 
Declare as superclass define as subclass example

Look, we just made a Dog but declared it as an Animal! Normally you would see this: 
Declare subclass define subclass

However, you can also declare a variable by its supertype or abstract type to make it more generic. Let's say you don't know what kind of animal you want: 
Declare abstract type only

Notice how the variable is not assigned to anything! We have an animal that has not been instantiate, and it does not equal anything. We can't create just Animals because they are abstract, so we must make a specific kind of animal, which is what we did with the example above by making the Animal be a new Dog.
So, which version of makeSound() would you use if you saw Animal animal = new Dog() ? Would you choose the Animal's version or the Dog's version? The answer is that Java will choose the true type, and the true type is the object that actually gets created. In this example, what we are really creating is a Dog, even though we are referencing the variable as an Animal.
Why in the world wouldn't we just do Dog dog = new Dog() ? The answer is that by using abstraction, you can actually group many different types of objects together. Let's see how we can use this concept for storing objects: 
Store objects in ArrayList by declared superclass

We could not do the above if the Cat objects and Dog objects were made the traditional way and not by referencing them as Animals.
It is very important you do not flip the reference and the true type! You could not do this: 
Declared subclass cannot be defined into the superclass

First of all, in our example, you cannot create Animal objects because they are abstract. Let's assume you could though. This is still illegal because a specific type cannot be the reference of a more broad type. Think about it this way: A dog is an animal but an animal is not necessarily a dog. The above example is basically saying that an Animal is a Dog, and this is not always true.
Polymorphism in Java allows you to fully control how you group objects together and gives you the power to make them as specific as you want. It is also the crucial part of object-oriented programming that allows you to build hierarchies of objects, objects that have a logical structure that makes sense in the real world. Because of polymorphism, you can create highly sophisticated programs in Java that are easy to read and are well organized. It does not guarantee an awesome organization of your code, but if you're careful it can help you immensely in doing so.
My final advice about polymorphism in Java is to practice! Practice making a bunch of abstract and regular classes. Create your own object structures. Make different objects extend each other. Write the same methods over and over again using different parameters and putting them in the parent classes and subclasses. Then, test out your objects by writing a main class that uses the classes and methods you write in different ways. By doing so, you will be on your way to mastering this highly abstract, highly powerful concept


FAQ's On Ploymorphism:


What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.

How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
  • In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
  • In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).


Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading.Runtime time polymorphism is done using inheritance and interface.
NoteFrom a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface


What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.

What is method overloading?
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Note:
  • Overloaded methods MUST change the argument list
  • Overloaded methods CAN change the return type
  • Overloaded methods CAN change the access modifier
  • Overloaded methods CAN declare new or broader checked exceptions
  • A method can be overloaded in the same class or in a subclass


What is method overriding?
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:
  • The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
  • You cannot override a method marked final
  • You cannot override a method marked static


What are the differences between method overloading and method overriding?
 Overloaded MethodOverridden Method
ArgumentsMust changeMust not change
Return typeCan changeCan’t change except for covariant returns
ExceptionsCan changeCan reduce or eliminate. Must not throw new or broader checked exceptions
AccessCan changeMust not make more restrictive (can be less restrictive)
InvocationReference type determines which overloaded version is selected. Happens at compile time.Object type determines which method is selected. Happens at runtime.


Can overloaded methods be override too?
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.

Is it possible to override the main method?
NO, because main is a static method. A static method can't be overridden in Java.

How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
	 // From subclass
		super.overriddenMethod();


What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:
  • You can only go back one level.
  • In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.


How do you prevent a method from being overridden?
To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
	                       public final void exampleMethod() {
                          //  Method statements
                          }



Enter your email address to get our daily JOBS & INTERVIEW FAQ's Straight to your Inbox.

Make sure to activate your subscription by clicking on the activation link sent to your email