[Go to site: main page, start]

0% found this document useful (0 votes)
45 views13 pages

Understanding Java Polymorphism

This document discusses Java polymorphism and provides examples to illustrate it. Polymorphism allows the same method to perform different operations depending on the object it is acting upon. It explains that polymorphism is achieved through method overriding, where a subclass defines a method with the same name as a parent class but different functionality. It also discusses method overloading and operator overloading as other ways to achieve polymorphism. Examples are provided to demonstrate polymorphism in action.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views13 pages

Understanding Java Polymorphism

This document discusses Java polymorphism and provides examples to illustrate it. Polymorphism allows the same method to perform different operations depending on the object it is acting upon. It explains that polymorphism is achieved through method overriding, where a subclass defines a method with the same name as a parent class but different functionality. It also discusses method overloading and operator overloading as other ways to achieve polymorphism. Examples are provided to demonstrate polymorphism in action.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Polymorphism

In this tutorial, we will learn about Java polymorphism and its implementation
with the help of examples.

Polymorphism is an important concept of object-oriented programming. It


simply means more than one form.

That is, the same entity (method or operator or object) can perform different
operations in different scenarios.
Example: Java Polymorphism
class Polygon {

// method to render a shape


public void render() {
[Link]("Rendering Polygon...");
}
}

class Square extends Polygon {

// renders Square
public void render() {
[Link]("Rendering Square...");
}
}

class Circle extends Polygon {

// renders circle
public void render() {
[Link]("Rendering Circle...");
}
}

class Main {
public static void main(String[] args) {

// create an object of Square


Square s1 = new Square();
[Link]();

// create an object of Circle


Circle c1 = new Circle();
[Link]();
}
}
Run Code
Output

Rendering Square...
Rendering Circle...

In the above example, we have created a superclass:  Polygon  and two


subclasses:  Square  and  Circle . Notice the use of the  render()  method.
The main purpose of the  render()  method is to render the shape. However, the
process of rendering a square is different than the process of rendering a
circle.
Hence, the  render()  method behaves differently in different classes. Or, we can
say  render()  is polymorphic.

Why Polymorphism?

Polymorphism allows us to create consistent code. In the previous example,


we can also create different methods:  renderSquare()  and  renderCircle()  to
render  Square  and  Circle , respectively.
This will work perfectly. However, for every shape, we need to create different
methods. It will make our code inconsistent.

To solve this, polymorphism in Java allows us to create a single


method  render()  that will behave differently for different shapes.

Note: The  print()  method is also an example of polymorphism. It is used to


print values of different types like  char ,  int ,  string , etc.
We can achieve polymorphism in Java using the following ways:

1. Method Overriding
2. Method Overloading
3. Operator Overloading

Java Method Overriding


During inheritance in Java, if the same method is present in both the
superclass and the subclass. Then, the method in the subclass overrides the
same method in the superclass. This is called method overriding.
In this case, the same method will perform one operation in the superclass
and another operation in the subclass. For example,

Example 1: Polymorphism using method overriding


class Language {
public void displayInfo() {
[Link]("Common English Language");
}
}

class Java extends Language {


@Override
public void displayInfo() {
[Link]("Java Programming Language");
}
}
class Main {
public static void main(String[] args) {

// create an object of Java class


Java j1 = new Java();
[Link]();

// create an object of Language class


Language l1 = new Language();
[Link]();
}
}
Run Code

Output:

Java Programming Language


Common English Language

In the above example, we have created a superclass named  Language  and a


subclass named  Java . Here, the method  displayInfo()  is present in
both  Language  and  Java .
The use of  displayInfo()  is to print the information. However, it is printing
different information in  Language  and  Java .
Based on the object used to call the method, the corresponding information is
printed.
Working of
Java Polymorphism

Note: The method that is called is determined during the execution of the
program. Hence, method overriding is a run-time polymorphism.

2. Java Method Overloading


In a Java class, we can create methods with the same name if they differ in
parameters. For example,

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

This is known as method overloading in Java. Here, the same method will
perform different operations based on the parameter.

Example 3: Polymorphism using method overloading


class Pattern {

// method without parameter


public void display() {
for (int i = 0; i < 10; i++) {
[Link]("*");
}
}

// method with single parameter


public void display(char symbol) {
for (int i = 0; i < 10; i++) {
[Link](symbol);
}
}
}

class Main {
public static void main(String[] args) {
Pattern d1 = new Pattern();

// call method without any argument


[Link]();
[Link]("\n");

// call method with a single argument


[Link]('#');
}
}
Run Code

Output:

**********

##########

In the above example, we have created a class named  Pattern . The class
contains a method named  display()  that is overloaded.

// method with no arguments


display() {...}

// method with a single char type argument


display(char symbol) {...}

Here, the main function of  display()  is to print the pattern. However, based on
the arguments passed, the method is performing different operations:
 prints a pattern of  * , if no argument is passed or
 prints pattern of the parameter, if a single  char  type argument is passed.

Note: The method that is called is determined by the compiler. Hence, it is


also known as compile-time polymorphism.

3. Java Operator Overloading


Some operators in Java behave differently with different operands. For
example,

 +  operator is overloaded to perform numeric addition as well as string


concatenation, and
 operators like  & ,  | , and  !  are overloaded for logical and bitwise
operations.
Let's see how we can achieve polymorphism using operator overloading.

The  +  operator is used to add two entities. However, in Java, the  +  operator
performs two operations.
1. When  +  is used with numbers (integers and floating-point numbers), it
performs mathematical addition. For example,
int a = 5;
int b = 6;

// + with numbers
int sum = a + b; // Output = 11

2. When we use the  +  operator with strings, it will perform string concatenation
(join two strings). For example,

String first = "Java ";


String second = "Programming";

// + with strings
name = first + second; // Output = Java Programming

Here, we can see that the  +  operator is overloaded in Java to perform two
operations: addition and concatenation.

Note: In languages like C++, we can define operators to work differently for
different operands. However, Java doesn't support user-defined operator
overloading.

Polymorphic Variables
A variable is called polymorphic if it refers to different values under different
conditions.

Object variables (instance variables) represent the behavior of polymorphic


variables in Java. It is because object variables of a class can refer to objects
of its class as well as objects of its subclasses.
Example: Polymorphic Variables
class ProgrammingLanguage {
public void display() {
[Link]("I am Programming Language.");
}
}

class Java extends ProgrammingLanguage {


@Override
public void display() {
[Link]("I am Object-Oriented Programming Language.");
}
}

class Main {
public static void main(String[] args) {

// declare an object variable


ProgrammingLanguage pl;

// create object of ProgrammingLanguage


pl = new ProgrammingLanguage();
[Link]();

// create object of Java class


pl = new Java();
[Link]();
}
}
Run Code

Output:

I am Programming Language.
I am Object-Oriented Programming Language.

In the above example, we have created an object variable  pl  of


the  ProgrammingLanguage  class. Here,  pl  is a polymorphic variable. This is
because,
 In statement  pl = new ProgrammingLanguage() ,  pl  refer to the object of
the  ProgrammingLanguage  class.
 And, in statement  pl = new Java() ,  pl  refer to the object of the  Java  class.

Java Polymorphism
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.

Like we specified in the previous chapter; Inheritance lets us inherit attributes


and methods from another class. Polymorphism uses those methods to
perform different tasks. This allows us to perform a single action in different
ways.

For example, think of a superclass called Animal that has a method


called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds -
And they also have their own implementation of an animal sound (the pig oinks,
and the cat meows, etc.):

Example
class Animal {

public void animalSound() {


[Link]("The animal makes a sound");

class Pig extends Animal {

public void animalSound() {

[Link]("The pig says: wee wee");

class Dog extends Animal {

public void animalSound() {

[Link]("The dog says: bow wow");

}
Remember from the Inheritance chapter that we use the extends keyword to
inherit from a class.

Now we can create Pig and Dog objects and call the animalSound() method on both


of them:

Example
class Animal {

public void animalSound() {

[Link]("The animal makes a sound");

}
class Pig extends Animal {

public void animalSound() {

[Link]("The pig says: wee wee");

class Dog extends Animal {

public void animalSound() {

[Link]("The dog says: bow wow");

class Main {

public static void main(String[] args) {

Animal myAnimal = new Animal(); // Create a Animal object

Animal myPig = new Pig(); // Create a Pig object

Animal myDog = new Dog(); // Create a Dog object

[Link]();

[Link]();

[Link]();

Common questions

Powered by AI

In Java polymorphism, method overriding involves redefining a method in a subclass that exists in its superclass, so the subclass method is called by objects of that subclass. Variable shadowing occurs when a field in a subclass has the same name as a field in its superclass, hiding the superclass's variable. While overriding affects methods and is resolved at runtime, shadowing affects fields (variables) and is resolved at compile time, meaning reference type determines which variable is accessed. This differentiation can lead to confusion if not carefully managed .

Polymorphism in Java offers several advantages, such as improved code maintainability, flexibility, and the ability to create reusable code by defining a common protocol for a group of related activities. This leads to cleaner and more consistent code, reducing redundancy and the risk of errors. A potential drawback is the increased complexity in understanding the flow of execution since the actual method implementation used is determined at runtime, which can complicate the debugging process if the class hierarchy is large or poorly documented .

Polymorphic variables enhance flexibility in Java programming by allowing a single variable to refer to objects of different classes at different times, especially within an inheritance hierarchy. For instance, an object variable of type ProgrammingLanguage can initially refer to an instance of the ProgrammingLanguage class and later to an instance of its subclass, Java. This capability means the exact method implementations that will execute are determined at runtime, facilitating dynamic method invocation and reducing coupling between code components .

Method overriding demonstrates polymorphism by allowing a subclass to provide a specific implementation of a method already defined in its superclass. The overridden method in the subclass is always invoked based on the actual object type at runtime rather than the reference type, which distinguishes it as run-time polymorphism. This dynamic method dispatch allows different method implementations to execute depending on the object's actual class during program execution .

Operator overloading in Java supports polymorphism by allowing some operators to perform various operations depending on their operands. For example, the '+' operator can perform numeric addition with integers, like 'int a = 5; int b = 6; int sum = a + b;', resulting in sum = 11. It also concatenates strings, such as 'String first = "Java "; String second = "Programming";', where 'String name = first + second;' results in 'Java Programming'. While Java doesn't allow user-defined operator overloading, predefined operators can exhibit polymorphic behavior .

Method overloading is a form of compile-time polymorphism that allows multiple methods in the same class to have the same name but different parameters. The compiler determines which method to execute at compile time based on the method signature. Unlike method overriding, which involves a base and derived class relationship, overloading operates within the same class and is resolved during compilation, making it compile-time polymorphism .

Polymorphism through inheritance leads to more scalable object-oriented programs by allowing new child classes to be added with minimal modification to existing code. For example, if a superclass Animal has a method animalSound(), various subclasses like Pig and Dog can provide their specific implementations. Future additions such as Cat or Bird simply extend Animal, with their sound implementations, without altering the existing codebase. This design promotes extending capabilities (scale) rather than altering the present system, enabling easier maintenance and scaling of features .

Java does not support user-defined operator overloading to maintain simplicity and prevent potential misuse that could complicate code readability and increase errors. This decision means that while certain operators in Java are overloaded for specific operations (like + for addition and concatenation), developers cannot define new behaviors for operators. Consequently, Java developers rely more on method overloading or specific methods to achieve polymorphic behavior instead of customizing operators, ensuring code clarity and reducing unexpected results .

Java polymorphism introduces both compile-time and runtime considerations that influence efficiency. Method overloading is resolved at compile-time and typically does not have a substantial runtime cost. However, method overriding, a form of runtime polymorphism, requires dynamic method lookup, which can incur a performance overhead compared to static binding. Despite this, the flexibility and dynamic behavior facilitated by runtime polymorphism often outweigh the minor performance costs, enabling more adaptable and maintainable code structures .

Java polymorphism is the ability of an object to take on many forms, specifically allowing a single method to perform differently based on the object it acts upon. This is achieved through mechanisms like method overriding and method overloading. It contributes to consistent code by allowing a single method, such as render(), to have a uniform name while performing varied operations across subclasses, like rendering different shapes without creating separate methods for each shape .

You might also like