Webinar Alert : Mastering  Manual and Automation Testing! - Reserve Your Free Seat Now

- Online IT Training Blogs -

What is Polymorphism in Java? Type of Polymorphism in Java with Example

What is Polymorphism in Java?

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. Polymorphism in Java Highlights:

  • Every object in Java passes a minimum of two IS-A tests, one for itself and one for the object class.
  • Static polymorphism in Java is achieved through method overloading at the compile time.
  • Dynamic polymorphism in Java is achieved through method overriding at the run time.

Polymorphism in Java with Examples

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. parent class 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. Polymorphism in Java

  • When the withdraw method for saving account is called, a method from the parent class is executed.
  • When the withdraw method from for the privileged account (overdraft facility) is called, withdraw method defined in the privileged class is executed. This is called the Polymorphism.

Static Polymorphism in Java

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: Flourish In The Software Testing Industry By Getting Certified With Selenium Automated Tools

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 Polymorphism in Java

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. Polymorphism in Java 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:

  • It is used to refer to an immediate parent class instance variable.
  • It is used to invoke an immediate parent class method.
  • It is used to invoke an immediate parent class constructor.

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: Salesforce looks to the future with Einstein artificial intelligence

What are the rules for Method Overriding?

  • The method should have the same name as of the parent class.
  • The method should have the same parameters as of the parent class.
  • There should be an IS-A relationship between subclass objects and parent class objects.

Facts to Consider:

  • A static method cannot be overridden, but it can be overloaded as per the requirement. A static method is bound with the class, whereas the instance method is bound with an object. Here static belongs to the class area, and instance belongs to the heap area.
  • The main method in Java cannot be overridden, but it can be overloaded.

Moving ahead, let us first discuss the comparison between dynamic and static polymorphism, method overloading, and method overriding.

Method Overloading vs. 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:

Void sum (int a, int b);

Void sum (int a, int b, int c);

Void sum (float a, double b);
Example:

Class x{

Public int sum() {

//some code

} }

Class Y extents x {

//overridden method

// signature is same

} }

 

 Static Polymorphism vs. Dynamic Polymorphism

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:

Void sum (int a, int b);

Void sum (float a, double b);

Void sum (int a, int b);

//compiler gives error
   
The other names for dynamic polymorphism are dynamic binding or runtime polymorphism. Example:

//reference of parent pointing to child object

Doctor obj = new surgeon ();

// method of child called

Obj.treatpatient();

 Instance Initializer Block

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: JanBask Training Gives a High Level of Business Analyst Training
  • It is created when an instance of the class is created.
  • It is invoked, once the constructor of the parent class is executed.
  • It comes in the same order in which they appear.

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.



fbicons FaceBook twitterTwitter lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    JanBask Training

    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.


  • fb-15
  • twitter-15
  • linkedin-15

Comments

Trending Courses

Cyber Security Course

Cyber Security

  • Introduction to cybersecurity
  • Cryptography and Secure Communication 
  • Cloud Computing Architectural Framework
  • Security Architectures and Models
Cyber Security Course

Upcoming Class

1 day 27 Sep 2024

QA Course

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing
QA Course

Upcoming Class

1 day 27 Sep 2024

Salesforce Course

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL
Salesforce Course

Upcoming Class

6 days 02 Oct 2024

Business Analyst Course

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum
Business Analyst Course

Upcoming Class

8 days 04 Oct 2024

MS SQL Server Course

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design
MS SQL Server Course

Upcoming Class

8 days 04 Oct 2024

Data Science Course

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning
Data Science Course

Upcoming Class

1 day 27 Sep 2024

DevOps Course

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing
DevOps Course

Upcoming Class

2 days 28 Sep 2024

Hadoop Course

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation
Hadoop Course

Upcoming Class

1 day 27 Sep 2024

Python Course

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation
Python Course

Upcoming Class

2 days 28 Sep 2024

Artificial Intelligence Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence Course

Upcoming Class

1 day 27 Sep 2024

Machine Learning Course

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning
Machine Learning Course

Upcoming Class

8 days 04 Oct 2024

 Tableau Course

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop
 Tableau Course

Upcoming Class

1 day 27 Sep 2024

Search Posts

Reset

Receive Latest Materials and Offers on Online IT Training Course

Interviews