What’s Polymorphism in Java?
Polymorphism in Java is the duty that performs a single motion in alternative ways.
So, languages that don’t support polymorphism should not ‘Object-Oriented Languages’, but ‘Object-Based Languages’. Ada, as an illustration, is one such language. Since Java supports polymorphism, it’s an Object-Oriented Language.
Polymorphism occurs when there may be inheritance, i.e., many classes are related.
Inheritance is a strong feature in Java. Java Inheritance lets one class acquire the properties and attributes of one other class. Polymorphism in Java allows us to make use of these inherited properties to perform different tasks. Thus, allowing us to attain the identical motion in many alternative ways.
What’s Polymorphism?
The derivation of the word Polymorphism is from two different Greek words- poly and morphs. “Poly” means quite a few, and “Morphs” means forms. So, polymorphism means innumerable forms. Polymorphism, subsequently, is probably the most significant features of Object-Oriented Programming.
Must Learn Core Java Topics
Real-Life Examples of Polymorphism
A person can have different relationships with different people. A lady could be a mother, a daughter, a sister, and a friend, all at the identical time, i.e. she performs other behaviors in several situations.
The human body has different organs. Every organ has a special function to perform; the guts is answerable for blood flow, the lungs for respiratory, the brain for cognitive activity, and the kidneys for excretion. So we now have a typical method function that performs in a different way depending upon the organ of the body.
Polymorphism in Java Example
A superclass named “Shapes” has a way called “area()”. Subclasses of “Shapes” may be “Triangle”, “circle”, “Rectangle”, etc. Each subclass has its way of calculating area. Using Inheritance and Polymorphism means, the subclasses can use the “area()” method to seek out the realm’s formula for that shape.
class Shapes {
public void area() {
System.out.println("The formula for area of ");
}
}
class Triangle extends Shapes {
public void area() {
System.out.println("Triangle is ½ * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
}
class Primary {
public static void foremost(String[] args) {
Shapes myShape = latest Shapes(); // Create a Shapes object
Shapes myTriangle = latest Triangle(); // Create a Triangle object
Shapes myCircle = latest Circle(); // Create a Circle object
myShape.area();
myTriangle.area();
myShape.area();
myCircle.area();
}
}
Output:
The formula for the realm of the Triangle is ½ * base * height
The formula for the realm of the Circle is 3.14 * radius * radius
class Shape {
public void draw() {
System.out.println("Drawing a shape");
}
}
class Circle extends Shape {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
@Override
public void draw() {
System.out.println("Drawing a square");
}
}
class Primary {
public static void foremost(String[] args) {
Shape s1 = latest Circle();
Shape s2 = latest Square();
s1.draw(); // Output: "Drawing a circle"
s2.draw(); // Output: "Drawing a square"
}
}
In this instance, we now have a base class Shape with a single method draw() that prints “Drawing a shape” to the console. We then create two subclasses, Circle and Square, that override the draw() method to print “Drawing a circle” and “Drawing a square” respectively.
Within the foremost method, we create two instances of the Shape class, s1 and s2, which are literally instances of the Circle and Square subclasses. After we call the draw() method on these objects, the proper implementation known as based on the actual sort of the thing, that is run-time polymorphism. This system will output: “Drawing a circle” and “Drawing a square”
In this instance, the draw() method is overridden within the subclasses, and this enables for this system to find out which method to make use of at runtime. That is often known as runtime polymorphism or dynamic polymorphism, Because at runtime the JVM determines the actual sort of the thing and calls the corresponding method.
Also Read: OOPs concepts in Java
Varieties of Polymorphism
You may perform Polymorphism in Java via two different methods:
- Method Overloading
- Method Overriding
What’s Method Overloading in Java?
Method overloading is the method that may create multiple methods of the identical name in the identical class, and all of the methods work in alternative ways. Method overloading occurs when there may be multiple approach to the identical name in the category.
Example of Method Overloading in Java
class Shapes {
public void area() {
System.out.println("Find area ");
}
public void area(int r) {
System.out.println("Circle area = "+3.14*r*r);
}
public void area(double b, double h) {
System.out.println("Triangle area="+0.5*b*h);
}
public void area(int l, int b) {
System.out.println("Rectangle area="+l*b);
}
}
class Primary {
public static void foremost(String[] args) {
Shapes myShape = latest Shapes(); // Create a Shapes object
myShape.area();
myShape.area(5);
myShape.area(6.0,1.2);
myShape.area(6,2);
}
}
Output:
Find area
Circle area = 78.5
Triangle area=3.60
Rectangle area=12
What’s Method Overriding in Java?
Method overriding is the method when the subclass or a toddler class has the identical method as declared within the parent class.
Example of Method Overriding in Java
class Vehicle{
//defining a way
void run(){System.out.println("Vehicle is moving");}
}
//Creating a toddler class
class Car2 extends Vehicle{
//defining the identical method as within the parent class
void run(){System.out.println("automotive is running safely");}
public static void foremost(String args[]){
Car2 obj = latest Car2();//creating object
obj.run();//calling method
}
}
Output:
Automobile is running safely
Also, Polymorphism in Java may be classified into two types, i.e:
- Static/Compile-Time Polymorphism
- Dynamic/Runtime Polymorphism
What’s Compile-Time Polymorphism in Java?
Compile Time Polymorphism In Java can be often known as Static Polymorphism. Moreover, the decision to the tactic is resolved at compile-time. Compile-Time polymorphism is achieved through Method Overloading. One of these polymorphism can be achieved through Operator Overloading. Nevertheless, Java doesn’t support Operator Overloading.
Method Overloading is when a category has multiple methods with the identical name, however the number, types, and order of parameters and the return sort of the methods are different. Java allows the user freedom to make use of the identical name for various functions so long as it may distinguish between them by the sort and variety of parameters. Take a look at a few of the necessary questions on run time polymorphism in java interview questions.
Example of Compile-Time Polymorphism in Java
package staticPolymorphism;
public class Addition
{
void sum(int a, int b)
{
int c = a+b;
System.out.println(“ Addition of two numbers :” +c); }
void sum(int a, int b, int e)
{
int c = a+b+e;
System.out.println(“ Addition of three numbers :” +c); }
public static void foremost(String[] args)
{
Addition obj = latest Addition();
obj.sum ( 30,90);
obj.sum(45, 80, 22);
}
}
What’s Runtime Polymorphism in Java?
Runtime polymorphism in Java can be popularly often known as Dynamic Binding or Dynamic Method Dispatch. On this process, the decision to an overridden method is resolved dynamically at runtime quite than at compile-time. You may achieve Runtime polymorphism via Method Overriding.
Method Overriding is completed when a toddler or a subclass has a way with the identical name, parameters, and return type because the parent or the superclass; then that function overrides the function within the superclass. In simpler terms, if the subclass provides its definition to a way already present within the superclass; then that function in the bottom class is alleged to be overridden.
Also, it ought to be noted that runtime polymorphism can only be achieved through functions and never data members.
Overriding is completed through the use of a reference variable of the superclass. The tactic to be called is set based on the thing which is being referred to by the reference variable. This can be often known as Upcasting.
Upcasting takes place when the Parent class’s reference variable refers to the thing of the kid class. For instance:
class A{}
class B extends A{}
A a=latest B(); //upcasting
Examples of Runtime Polymorphism in Java
Example 1:
In this instance, we’re creating one superclass Animal and three subclasses, Herbivores, Carnivores, and Omnivores. Subclasses extend the superclass and override its eat() method. We’ll call the eat() method by the reference variable of Parent class, i.e. Animal class. Because it refers back to the base class object and the bottom class method overrides the superclass method; the bottom class method is invoked at runtime. As Java Virtual Machine or the JVM and never the compiler determines method invocation, it’s, subsequently, runtime polymorphism.
class Animal{
void eat(){
System.out.println("Animals Eat");
}
}
class herbivores extends Animal{
void eat(){
System.out.println("Herbivores Eat Plants");
}
}
class omnivores extends Animal{
void eat(){
System.out.println("Omnivores Eat Plants and meat");
}
}
class carnivores extends Animal{
void eat(){
System.out.println("Carnivores Eat meat");
}
}
class foremost{
public static void foremost(String args[]){
Animal A = latest Animal();
Animal h = latest herbivores(); //upcasting
Animal o = latest omnivores(); //upcasting
Animal c = latest carnivores(); //upcasting
A.eat();
h.eat();
o.eat();
c.eat();
}
}
Output:
Animals eat
Herbivores Eat Plants
Omnivores Eat Plants and meat
Carnivores eat meat
Example 2:
In this instance, we’re creating one superclass Hillstations and three subclasses Manali, Mussoorie, Gulmarg. Subclasses extend the superclass and override its location() and famousfor() method. We’ll call the placement() and famousfor() method by the Parent class’, i.e. Hillstations class. Because it refers back to the base class object and the bottom class method overrides the superclass method; the bottom class method is invoked at runtime. Also, as Java Virtual Machine or the JVM and never the compiler determines method invocation, it’s runtime polymorphism.
class Hillstations{
void location(){
System.out.println("Location is:");
}
void famousfor(){
System.out.println("Famous for:");
}
}
class Manali extends Hillstations {
void location(){
System.out.println("Manali is in Himachal Pradesh");
}
void famousfor(){
System.out.println("It's Famous for Hadimba Temple and adventure sports");
}
}
class Mussoorie extends Hillstations {
void location(){
System.out.println("Mussoorie is in Uttarakhand");
}
void famousfor(){
System.out.println("It's Famous for education institutions");
}
}
class Gulmarg extends Hillstations {
void location(){
System.out.println("Gulmarg is in J&K");
}
void famousfor(){
System.out.println("It's Famous for skiing");
}
}
class foremost{
public static void foremost(String args[]){
Hillstations A = latest Hillstations();
Hillstations M = latest Manali();
Hillstations Mu = latest Mussoorie();
Hillstations G = latest Gulmarg();
A.location();
A.famousfor();
M.location();
M.famousfor();
Mu.location();
Mu.famousfor();
G.location();
G.famousfor();
}
}
Output:
Location is:
Famous for:
Manali is in Himachal Pradesh
It’s Famous for Hadimba Temple and adventure sports
Mussoorie is in Uttarakhand
It’s Famous for education institutions
Gulmarg is in J&K
It’s Famous for skiing
Example of run-time polymorphism in java
We’ll create two classes Automobile and Innova, Innova class will extend the automotive class and can override its run() method.
class Automobile
{
void run()
{
System.out.println(“ running”);
}
}
class innova extends Automobile
{
void run();
{
System.out.println(“ running fast at 120km”);
}
public static void foremost(String args[])
{
Automobile c = latest innova();
c.run();
}
}
One other example for run-time polymorphism in Java
class automotive
{
int speedlimit = 125;
}
class innova extends automotive
{
int speedlimit = 135;
public static void foremost(String args[])
{
automotive obj = latest innova();
System.out.println(obj.speedlimit);
}
Runtime polymorphism with multilevel inheritance
class grandfather
{
void swim()
{
System.out.println(“ Swimming”);
}
}
class father extends grandfather
{
void swim()
{
System.out.println(“ Swimming in river”);
}
}
class son extends father
{
void swim()
{
System.out.println(“ Swimming in pool”);
}
public static void foremost(String args[])
{
grandfather f1,f2,f3;
f1 =latest grandfather();
f2 = latest father();
f3 = latest son();
f1.swim();
f2.swim();
f3.swim():
}
}
, ,
One other runtime polymorphism with multilevel inheritance example
class soundAnimal
{
public void Sound()
{
System.out.println("Different sounds of animal"); }
}
class buffalo extends soundAnimal
{
public void Sound()
{
System.out.println("The buffalo sound- gho,gho"); }
}
class snake extends soundAnimal
{
public void Sound()
{
System.out.println("The snake sound- his,his"); }
}
class tiger extends soundAnimal
{
public void Sound()
{
System.out.println("The tiger sounds- roooo, rooo"); }
}
public class Animal Primary
{
public static void foremost(String[] args)
{
soundAnimal Animal = latest soundAnimal(); soundAnimal buffalo = latest buffalo();
soundAnimal snake = latest snake();
soundAnimal tiger = latest tiger();
Animal.Sound();
buffalo.Sound();
snake.Sound();
tiger.Sound();
}
}
We hope you bought an idea about runtime and compile-time polymorphism.
Polymorphic Subtypes
Subtype mainly signifies that a subtype can function one other type’s subtype, sounds a bit complicated?
Let’s understand this with the assistance of an example:
Assuming we now have to attract some arbitrary shapes, we are able to introduce a category named ‘shape’ with a draw() method. By overriding draw() with other subclasses corresponding to circle, square, rectangle, trapezium, etc we are going to introduce an array of type ‘shape’ whose elements store references will confer with ‘shape’ subclass references. Next time, we are going to call draw(), all shapes instances draw () method will probably be called.
This Subtype polymorphism generally relies on upcasting and late binding. A casting where you forged up the inheritance hierarchy from subtype to a supertype is termed upcasting.
To call non-final instance methods we use late binding. Briefly, a compiler shouldn’t perform any argument checks, type checks, method calls, etc, and leave the whole lot on the runtime.
What’s Polymorphism in Programming?
Polymorphism in programming is defined usage of a single symbol to represent multiple differing kinds.
What’s Polymorphism Variables?
A polymorphic variable is defined as a variable that may hold values of differing kinds through the course of execution.
Why use Polymorphism in Java?
Polymorphism in Java makes it possible to put in writing a way that may accurately process a lot of several types of functionalities which have the identical name. We may also gain consistency in our code through the use of polymorphism.
Benefits of Polymorphism in Java
- It provides reusability to the code. The classes which might be written, tested and implemented may be reused multiple times. Moreover, it saves quite a lot of time for the coder. Also, the one can change the code without affecting the unique code.
- A single variable may be used to store multiple data values. The worth of a variable you inherit from the superclass into the subclass may be modified without changing that variable’s value within the superclass; or some other subclasses.
- With lesser lines of code, it becomes easier for the programmer to debug the code.
Characteristics of Polymorphism
Polymorphism has many other characteristics apart from Method Overloading and Method Overriding. They include:
- Coercion
- Internal Operator Overloading
- Polymorphic Variables or Parameters
1. Coercion
Coercion deals with implicitly converting one sort of object right into a latest object of a special kind. Also, this is completed routinely to stop type errors within the code.
Programming languages corresponding to C, java, etc support the conversion of value from one data type to a different data type. Data type conversions are of two types, i.e., implicit and explicit.
Implicit type conversion is routinely done in this system and this sort of conversion can be termed coercion.
For instance, if an operand is an integer and one other one is in float, the compiler implicitly converts the integer into float value to avoid type error.
Example:
class coercion {
public static void foremost(String[] args) {
Double area = 3.14*5*7;
System.out.println(area);
String s = "completely satisfied";
int x=5;
String word = s+x;
System.out.println(word);
}
}
Output:
109.9
happy5
2. Internal Operator Overloading
In Operator Overloading, an operator or symbol behaves in additional ways than one depending upon the input context or the sort of operands. It’s a characteristic of static polymorphism. Although Java doesn’t support user-defined operator overloading like C++, where the user can define how an operator works for various operands, there are few instances where Java internally overloads operators.
Operator overloading is the concept of using the operator as per your alternative. Due to this fact, an operator symbol or method name may be used as a ‘user-defined’ type as per the necessities.
For instance, ‘+’ may be used to perform the addition of numbers (same data type) or for concatenation of two or more strings.
Within the case of +, may be used for addition and likewise for concatenation.
For instance:
class coercion {
public static void foremost(String[] args) {
String s = "completely satisfied";
String s1 = "world";
int x=5;
int y=10;
System.out.println(s+s1);
System.out.println(x+y);
}
}
Output :
Similarly, operators like! &, and | are also within the overload position for logical and bitwise operations. In each of those cases, the sort of argument will resolve how the operator will interpret.
3. Polymorphic Variables or Parameters
In Java, the thing or instance variables represent the polymorphic variables. It’s because any object variables of a category can have an IS-A relationship with their very own classes and subclasses.
The Polymorphic Variable is a variable that may hold values of differing kinds through the time of execution.
Parametric polymorphism specifies that while class declaration, a field name can associate with differing kinds, and a way name can associate with different parameters and return types.
For instance:
class Shape
{
public void display()
{
System.out.println("A Shape.");
}
}
class Triangle extends Shape
{
public void display()
{
System.out.println("I'm a triangle.");
}
}
class Primary{
public static void foremost(String[] args)
{
Shape obj;
obj = latest Shape();
obj.display();
obj = latest Triangle();
obj.display();
}
}
Output:
A Shape.
I’m a triangle.
Here, the obj object is a polymorphic variable. It’s because the superclass’s same object refers back to the parent class (Shape) and the kid class (Triangle).
Problems with Polymorphism
With a lot of benefits, there are also just a few disadvantages of polymorphism.
- Polymorphism is sort of difficult while implementation.
- It tends to cut back the readability of the code.
- It raises some serious performance issues in real-time as well.
Type Identification During Downcasting
Downcasting is termed as casting to a toddler type or casting a standard type to a person type.
So, we use downcasting at any time when we want to access or understand the behaviour of the subtypes.
Example,
It is a hierarchical example
Food> Vegetable> Ladyfinger, Tomato
Here, tomato and ladyfinger are two subclasses.
In downcasting, we narrow the sort of objects, which implies we’re converting common type to individual type.
Vegetable vegetable = latest Tomato();
Tomato castedTomato = (Tomato) vegetable;
Here we’re casting common type to a person type, superclass to subclass which isn’t possible directly in java.
We explicitly tell the compiler what the runtime sort of the thing is.
Fragile base class problem
Fragile base class problem is nothing but a fundamental architectural problem.
Sometimes the improper design of a parent class can lead a subclass of a superclass to make use of superclass in some unpredicted ways.
The fragility of inheritance will result in broken codes even when all the standards is met.
This architectural problem is termed as a fragile base class problem in object-oriented programming systems and language.
Mainly, the explanation for the delicate base problem is that the developer of the bottom class has no idea of the subclass design. There isn’t any solution yet for this problem.
Conclusion
We hope you could have gotten a basic idea of polymorphism in Java and the way we use it in addition to problems related to them.
Hence, this brings us to the tip of the blog on Polymorphism in Java. Moreover, to learn more about programming and other related concepts, take a look at the courses on Great Learning Academy and PG Programs in Software Engineering.
Also, when you are preparing for Interviews, take a look at these Interview Questions for Java to ace it like a professional.
So, don’t stop your journey of learning. Also, don’t forget to upskill and reskill yourself. Keep exploring and continue to learn.
Regularly Asked Questions
One in every of the OOPs features that enables us to perform a single motion in various ways is often known as polymorphism in Java. For instance, we now have a category Animal with a way sound(). It is a generic class and so we cannot give it an implementation corresponding to: Meow, Oink, Roar, etc.
The 4 sorts of polymorphism are:
– Runtime or Subtype polymorphism
– Overloading or Parametric polymorphism
– Compile-time or Ad hoc polymorphism
– Casting or Coercion polymorphism
One in every of the core concepts of OOP or object-oriented programming, polymorphism describes situations through which a particualr thing occurs in several forms. In computer science, polymorphism describes an idea that enables us to access several types of objects through the identical interface.
In object-oriented programming, overriding is a feature that enables a subclass or child class to offer a particular implementation of a way that’s already provided by certainly one of its superclasses or parent classes.
If two or more methods in the identical class have the identical name, but have different parameters, that is often known as Overloading. In case of Overriding, a way signature (name and parameters) are present in the identical superclass and the kid class.
Engaging within the study of Java programming suggests a keen interest within the realm of software development. For those embarking upon this journey with aspirations towards a profession on this field, it is suggested to explore the next pages as a way to acquire a comprehensive understanding of the event profession path: