0% found this document useful (0 votes)
1 views

Ch5 Polymorphism

Chapter 5 discusses polymorphism in Java, defining it as the ability of an object to take on many forms through method overloading and overriding. It highlights the importance of polymorphism in enabling different behaviors based on data types and the use of inheritance. Examples illustrate how method overloading allows multiple methods with the same name but different parameters, while method overriding allows a subclass to provide a specific implementation of a method defined in its parent class.

Uploaded by

Ebiyo Faf
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Ch5 Polymorphism

Chapter 5 discusses polymorphism in Java, defining it as the ability of an object to take on many forms through method overloading and overriding. It highlights the importance of polymorphism in enabling different behaviors based on data types and the use of inheritance. Examples illustrate how method overloading allows multiple methods with the same name but different parameters, while method overriding allows a subclass to provide a specific implementation of a method defined in its parent class.

Uploaded by

Ebiyo Faf
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

1

CHAPTER 5 : POLYMORPHISM

 Introduction
Polymorphism is the ability of an object to take on many forms. In other words, polymorphism
allows us to define one interface and have multiple implementations.
Polymorphism can be elaborated as:
 An operation may exhibit different behaviour in different instances.
 The behaviour depends on the types of data used in the operation.
 It plays an important role in allowing objects having different internal structures to share
the same external interface.
 Polymorphism is extensively used in implementing inheritance.
For instance, even if we have a variable with the type of a parent class, we can assign it to a child
class and we can call overridden methods in the child class using that variable.
Let's see an example.

class Fruit {
public void show() {
System.out.println("Fruit");
}
}

class Banana extends Fruit {


//method overriden
public void show() {
System.out.println("Banana");
}
public void makeBananaTree() {
System.out.println("Making a tree");
}
}

public class Application { OUTPUT:


public static void main(String[] args) {
Fruit banana = new Banana(); Banana
banana.show();

}
}

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


2

class Shape {
void draw() { }
}

class Circle extends Shape {


private int x, y, r;
Circle(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}

void draw() {
System.out.println("Drawing circle (" + x + ", "+ y + ", " + r + ")");
}
}

class Rectangle extends Shape {


private int x, y, w, h;

Rectangle(int x, int y, int w, int h)


{
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}

void draw() {
System.out.println("Drawing rectangle (" + x + ", "+ y + ", " + w + "," + h + ")");
}
}

class ShapesMain {
public static void main(String[] args) {
Shape[] shapes = { new Circle(10, 20, 30),
new Rectangle(20, 30, 40, 50) };
for (int i = 0; i < shapes.length; i++)
shapes[i].draw();
}
}

The declaration of the shapes array demonstrates upcasting. The Circle and Rectangle references
are stored in shapes[0] and shapes[1] and are upcast to typeShape. Each
of shapes[0] and shapes[1] is regarded as a Shape instance: shapes[0] isn't regarded as
a Circle; shapes[1] isn't regarded as a Rectangle.
Late binding is demonstrated by the shapes[i].draw(); expression. When i equals 0, the compiler-
generated instruction causes Circle's draw() method to be called. When i equals 1, however, this
instruction causes Rectangle's draw() method to be called. This is the essence of subtype
polymorphism.

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


3

 Types of Polymorphism in JAVA:


Polymorphism

Method Overloading Method Overriding

1) Method Overloading (Compile-time Polymorphism or Static


polymorphism)
In Java, it is possible to define two or more methods of same name in a class, provided that there
argument list or parameters are different. This concept is known as Method Overloading.
Argument lists could differ in –
a) Number of parameters.
b) Data type of parameters.
c) Sequence of Data type of parameters.

Example 1: Overloading – Different Number of parameters in argument list


When methods name are same but number of arguments are different.

class DisplayOverloading {
public void disp(char c) {
System.out.println(c);
}
public void disp(char c, int num) {
System.out.println(c + " "+num);
}
}
class Sample {
public static void main(String args[]) {
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
Output:
}
a
}
a 10

In the above example – method disp() has been overloaded based on the number of arguments.
We have two definition of method disp(), one with one argument and another with two arguments.

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


4

Example 2: Overloading – Difference in data type of arguments


In this example, method disp() is overloaded based on the data type, one with char argument and
another with int argument.

class DisplayOverloading2{
public void disp(char c) {
System.out.println(c);
}
public void disp(int c) {
System.out.println(c);
}
}

class Sample2{
public static void main(String args[]) {
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
Output:
}
a
} 5

Example3: Overloading – Sequence of data type of arguments


Here method disp() is overloaded based on sequence of data type of arguments – Both the
methods have different sequence of data type in argument list. First method is having argument
list as (char, int) and second is having (int, char). Since the sequence is different, the method can
be overloaded without any issues.

class DisplayOverloading3 {
public void disp(char c, int num) {
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c) {
System.out.println("I’m the second definition of method disp" );
}
}
class Sample3{
public static void main(String args[]) {
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y'); Output:
} I’m the first definition of method disp
} I’m the second definition of method disp

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


5

class DemoOverload{
public int add(int x, int y){ return x+y; }
public int add(int x, int y, int z){ return x+y+z; }
public int add(double x, int y){ return (int)x+y; }
public int add(int x, double y){ return x+(int)y; }
}

class OverloadingMain{
public static void main(String[] args){
DemoOverload demo=new DemoOverload();
System.out.println(demo.add(2,3)); //method 1 called
System.out.println(demo.add(2,3,4)); //method 2 called
System.out.println(demo.add(2,3.4)); //method 4 called
System.out.println(demo.add(2.5,3)); //method 3 called
}
}

Lets see few Valid/invalid cases of method overloading


Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both methods are having same
number, data types and same sequence of data types in arguments.
Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case for overloading. Here data types of arguments are different.
Case 3:
int mymethod(int a, int b)
int mymethod(int num)
Result: Perfectly fine. Valid case for overloading. Here number of arguments are different.
Case 4:
float mymethod(int a, float b)
float mymethod(float var1, int var2)
Result: Perfectly fine. Valid case for overloading. Sequence of the data types are different, first
method is having (int, float) and second is having (float, int).
Case 5:
int mymethod(int a, int b)
float mymethod(int var1, int var2)
Result: Compile time error. Argument lists are exactly same. Even though return type of methods
are different, it is not a valid case. Since return type of method doesn’t matter while overloading a
method.

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


6

Rules for Method Overloading


1. Overloaded method should always be the part of the same class (can also take place in
sub class), with same name but different parameters.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. The parameters may differ in their type or number, or in both.
5. They may have the same or different return types.
Guess the answers before checking it at the end of programs:

Question 1 – return type, method name and argument list same.


class Demo {
public int myMethod(int num1, int num2){
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2) {
System.out.println("Second myMethod of class Demo");
return var1-var2;
}}
class Sample4 {
public static void main(String args[]) {
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}}

Answer: It will throw a compilation error: More than one method with same name and
argument list cannot be defined in a same class.

Question 2 – return type is different. Method name & argument list same.
class Demo2 {
public double myMethod(int num1, int num2) {
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2) {
System.out.println("Second myMethod of class Demo");
return var1-var2;
}}
class Sample5 {
public static void main(String args[]) {
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}}

Answer: It will throw a compilation error: More than one method with same name and
argument list cannot be given in a class even though their return type is different. Method
return type doesn’t matter in case of overloading.

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


7

2) Method Overriding (Runtime Polymorphism or Dynamic Polymorphism)


Declaring a method in subclass which is already present in parent class is known as method
overriding. The benefit of overriding is: ability to define a behaviour that's specific to the subclass
type which means a subclass can implement a parent class method based on its requirement. In
object-oriented terms, overriding means to override the functionality of an existing method.

Example:
Let us look at an example.

class Animal{
public void move(){
System.out.println("Animals can move");
}
}

class Dog extends Animal{


public void move(){
System.out.println("Dogs can walk and run");
}
}

public class TestDog{


public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}

This would produce the following result:


Animals can move
Dogs can walk and run
In the above example, we can see that the even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time, the check is made on the
reference type. However, in the runtime, JVM figures out the object type and would run the
method that belongs to that particular object.
Therefore, in the above example, the program will compile properly since Animal class has the
method move. Then, at the runtime, it runs the method specific for that object.

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


8

Consider the following example :

class Animal{
public void move(){
System.out.println("Animals can move");
}
}

class Dog extends Animal{


public void move(){
System.out.println("Dogs can walk and run");
}
public void bark(){
System.out.println("Dogs can bark");
}
}

public class TestDog{


public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
b.bark();
}
}

This would produce the following result:


TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^
This program will throw a compile time error since b's reference type Animal doesn't have a
method by the name of bark.

Rules for Method Overriding:


1. Applies only to inherited methods
2. Object type (NOT reference variable type) determines which overridden method will be
used at runtime

3. Overriding method can have different return type (if return types are not primitive) or user
defined return types( object types)

4. Static and final methods cannot be overridden


5. Constructors cannot be overridden

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


9

6. It is also known as Runtime polymorphism.

Overriding method with different return type (user defined types)

Method overloading Vs method overriding

A list of differences between method overloading and method overriding are


given below:

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE


10

Prepared by: Dr. Obsa G. WOLLEGA UNIVERSITY, NEKEMTE

You might also like