Black Friday Deal : Up to 40% OFF! + 2 free self-paced courses + Free Ebook - SCHEDULE CALL
Polymorphism literally means “a state of having many shapes
” or “the capacity of taking different forms
.” When this concept is applied to object-oriented programming in Java, it describes the ability of a programming language to process objects of different types and classes through a uniform interface. Polymorphism in Java is divided into two major categories, compile-time polymorphism (static binding), run time polymorphism (dynamic binding). Method Overloading is an example of static polymorphism, and Method Overriding is an example of dynamic polymorphism. Highlights:
Example 1 One best example of Polymorphism in Java is how a parent class object refers to a child class object. If there is an object that satisfies more than one “IS-A” relationship is polymorphic in nature. For example, let us consider “Animal” as the parent class and “Dog” is a child class of Parent class. So, any Dog is an animal. Here, Dog as the subclass satisfies the IS-A relationship for its own parent class “Animal” and it is polymorphic. It would not be saying wrong that each object is polymorphic in nature as it passes an IS-A test for itself and for object class too.
Example 2 Another example is the smartphone that you use for communication. Here, the smartphone is one, but communication modes can be different. It can be a call, e-mail, text message, picture messages, videos, etc. in simple words, the goal is communication, but approaches are different.
This is called the Polymorphism.
Example 3 Take an example of a bank account defined with two functions, deposit and withdraw. Account has two subclasses. The operations of both functions are the same for Saving and checking account. So, the inherited method from the “Account” class will work. Here is the pictorial representation for your reference. There is a change in software requirements specifications that is common in IT industries. You should add the overdraft facility for a privileged bank account. With the help of the overdraft facility, you may withdraw more than the actual amount available in the account. So, the withdraw method should be refreshed again, but the piece of code in Saving and checking accounts are not required to change. This is the biggest advantage of OOPs.
In Java, Static or compile-time polymorphism is achieved through method overloading. At compile time, Java knows which method should be invoked through method signatures. So, it is also called static binding or compile-time polymorphism. You must be wondering what is method overloading in Java. Let us discuss in detail below.
Read: 3 Habits to Overcome Your Self- doubts to Join IT
Method Overloading means there are multiple methods in a class having different types, several arguments, order, etc. If we can perform single an operation to multiple methods together, it increases the overall readability of the program. For example, you want to add several arguments for different methods having a different number of arguments. One method is written as A (int, int) with two parameters and another method is written as B (int, int, int) with three parameters then it may be difficult for programmers understanding the behavior of method because its name differs. You should use the Method Overloading concept to evaluate the program quickly. It increases the overall readability of the program and speeds up the execution as well. Method Overloading can be achieved in two popular ways, either through changing number of arguments or by changing the data types. Keep in mind that method overloading cannot be achieved by changing the return data types of methods.
Dynamic or run time polymorphism in Java is achieved through method overriding. It is the mechanism by which multiple methods are defined with the same name or signature in the superclass and subclass. The call to an overridden method is resolved at the run time. Here is the example of dynamic polymorphism for your reference. A reference variable of superclass refers to an object in the subclass.
Doctor obj = new surgeon();
Consider the statement:
Obj.treatpatient();
Here “obj” is a reference variable of super class but pointing to a method of child class as given below. Here, obj.treatPatient()
will execute treatPatient()
method of the sub-class – Surgeon. Even though “obj” is a reference to Doctor, it calls the Surgeon method, as it points to a Surgeon object. It is decided at the runtime, so it is called the dynamic or runtime polymorphism.
Super keyword in Java: What to do when treatPatient()
method in the surgeon class want to execute functionalities defined in the Doctor class then want to perform its own specific functionality? You should use the super keyword here to access methods of the parent class from the child class. The code could be written as below.
Treatpatient()
{
Super.treatpatient();
//add code specific to surgeon
}
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object. Every time you are creating an instance of a subclass, an instance of the parent class is also created which is referred by super reference variable. The major benefits of the super keyword in Java include:
Method Overriding in Java So, what we meant by Method Overriding exactly? If a subclass has the same method declared in the superclass, it is named as the method overriding in Java. In simple words, if subclass offers the specific implementation of the method that has been declared by one of its parent class, the process is named as the method overriding here.
Read: Top Short Term Courses to Invest in After Graduation
What are the rules for Method Overriding?
Facts to Consider:
Moving ahead, let us first discuss the comparison between dynamic and static polymorphism, method overloading, and method overriding.
Method Overloading | Method Overriding |
It is performed for the same class where multiple methods have the same name but different signatures. | When one of the methods in the superclass is redefined in the subclass, but signatures for all methods remain the same. |
Example:
|
Example:
|
Static Polymorphism | Dynamic Polymorphism |
It is related to the method overloading. | It is related to the method overriding. |
If there are any errors, they are resolved at the compiled time. Here, the code is not executed at the compile time, so it is static in nature. | Here, methods are invoked at the runtime when the code is under execution. Hence the name is dynamic. |
The other names for static polymorphism are static binding or compile time polymorphism. Example:
|
The other names for dynamic polymorphism are dynamic binding or runtime polymorphism. Example:
|
An instance initializer block in Java is used to initialize the instance data members. The instance initializer block needs to run every time an object of the class is created. This initialization can be performed either directly or indirectly as per the requirement. Consider a situation where you want to perform multiple operations while assigning values to instance data members, for example, defining a loop for complex error or array handling. There are three places where you can perform operations in Java. These are Method, constructor, block, etc.
class Bike8{
int speed;
Bike8(){System.out.println("constructor is invoked");}
{System.out.println("instance initializer block invoked");}
public static void main(String args[]){
Bike8 b1=new Bike8();
Bike8 b2=new Bike8();
}
}
In the above example, what is invoked first? Here is the output of the program:
Output:instance initializer block invoked
Constructor is invoked
Instance initializer block invoked
Constructor is invoked
It seems that instance initializer block is invoked first but it is not true. Logically, the constructor is invoked first and instance initializer block is invoked at the time of object creation. Rules, for instance, initializer block: Here are the rules, for instance, initializer block as defined below:
Read: Salesforce Added New Features in Health Cloud
Final keywords in Java
This blog is not complete if you are not sure of the final keywords in Java. Every time you are writing a polymorphic program, you have to use super, final, instance initializer block keywords as per the requirement. The final keyword in Java is used for restricting users. It can be used in many contexts like methods, variables, classes, etc. The final keyword is applied to variables. If there is a final variable having no value is called uninitialized final keyword or blank final keyword. If we add the static keyword before Final keyword, then it can be used for initializing static block only. It is not possible to change the value of a final variable; it will be constant. A final method cannot be overridden but can be inherited if required.
Summary:
With the discussion above, you must now have a clear idea about Polymorphism in Java and related concepts too. To practice program on the concept and how to use it for your application, you should join the Java certification program online and learn Java concepts in detail from basic to advance. Also, you should practice real-life problems and find a solution for the same using polymorphism concept. Java is robust programming with unexpected future growth. So, the demand for Java professionals is growing tremendously. If you are also planning to start a career in Java, then JanBask Training can help you with the detailed and structured training program online and taking your career to the next level.
A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.
Cyber Security
QA
Salesforce
Business Analyst
MS SQL Server
Data Science
DevOps
Hadoop
Python
Artificial Intelligence
Machine Learning
Tableau
Search Posts
Related Posts
PMP® Exam Self-Assessment Test 646.8k
Why Choose JanBask Training For Oracle DBA Training 155.3k
How scrum master certification can boost your career rapidly? 650.2k
The competition between Salesforce and Microsoft is intensifying continuously 785.9k
Flourish In The Software Testing Industry By Getting Certified With Selenium Automated Tools 740.3k
Receive Latest Materials and Offers on Online IT Training Course
Interviews