Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
17 views11 pages

POLYMORPHISM8

Polymorphism in Java allows objects to take on multiple forms, primarily through method overloading and overriding. Compile-time polymorphism is achieved via method overloading, while runtime polymorphism is achieved through method overriding, enabling dynamic method resolution. The document also discusses the differences between function overloading and overriding, along with practical examples and the use of the 'super' keyword.

Uploaded by

buushman151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views11 pages

POLYMORPHISM8

Polymorphism in Java allows objects to take on multiple forms, primarily through method overloading and overriding. Compile-time polymorphism is achieved via method overloading, while runtime polymorphism is achieved through method overriding, enabling dynamic method resolution. The document also discusses the differences between function overloading and overriding, along with practical examples and the use of the 'super' keyword.

Uploaded by

buushman151
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

POLYMORPHISM IN JAVA

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all
Java objects are polymorphic since any object will pass the IS-A test for their own type and for the
class Object.
It is important to know that the only possible way to access an object is through a reference variable.
A reference variable can be of only one type. Once declared, the type of a reference variable cannot
be changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The
type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A
reference variable can be declared as a class or interface type.

Real-Life Examples of Polymorphism

An individual can have different relationships with different people. A woman can be a mother, a
daughter, a sister, a friend, all at the same time, i.e. she performs other behaviors in different
situations.

The human body has different organs. Every organ has a different function to perform; the heart
is responsible for blood flow, lungs for breathing, brain for cognitive activity, and kidneys for
excretion. So we have a standard method function that performs differently depending upon the
organ of the body.

Polymorphism in Java can be classified into two types;

1. Static/Compile-Time Polymorphism
2. Dynamic/Runtime Polymorphism

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 1


Compile Time Polymorphism In Java is also known as Static Polymorphism. Furthermore,
the call to the method is resolved at compile-time. Compile-Time polymorphism is achieved
through Method Overloading. Method Overloading is when a class has multiple methods with
the same name, but the number, types, and order of parameters and the return type of the methods
are different. Java allows the user freedom to use the same name for various functions as long as
it can distinguish between them by the type and number of parameters.

Advantage of method overloading

Method overloading increases the readability of the program.

Runtime polymorphism in Java is also popularly known as Dynamic Binding or Dynamic


Method Dispatch. In this process, the call to an overridden method is resolved dynamically at
runtime rather than at compile-time. You can achieve Runtime polymorphism via Method
Overriding.

Method Overriding is done when a child or a subclass has a method with the same name,
parameters, and return type as the parent or the superclass; then that function overrides the
function in the superclass. In simpler terms, if the subclass provides its definition to a method
already present in the superclass; then that function in the base class is said to be overridden.

Advantage of Java Method Overriding


The main advantage of method overriding is that it allows the main class to define methods which
would be common to all of the subclasses and it also allows the subclasses to define their own specific
implementation of some or all of those methods.

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 2


Function Overloading VS Function Overriding

1. Inheritance: Overriding of functions occurs when one class is inherited from another class.
Overloading can occur without inheritance.
2. Function Signature: Overloaded functions must differ in function signature ie either number
of parameters or type of parameters should differ. In overriding, function signatures must be
same.
3. Scope of functions: Overridden functions are in different scopes; whereas overloaded
functions are in same scope.
4. Behavior of functions: Overriding is needed when derived class function has to do some added
or different job than the base class function. Overloading is used to have same name functions
which behave differently depending upon parameters passed to them.

Implementation of Compile time polymorphism (Method Overloading)

Different ways to overload the method

There are three ways to overload the method in java

1. By changing number of arguments


2. By changing the data type
3. By changing the Order of the parameters

1. By changing number of arguments

In this type of function overloading, we define two functions with same names but different
number of parameters of the same type.

public class Addition


{
void sum(int a, int b)
{
int c = a+b;

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 3


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 main(String[] args)
{
Addition obj = new Addition();
obj.sum ( 30,90);
obj.sum(45, 80, 22);
}
}

Prompt the User to input:


import java.util.Scanner;
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 main(String[] args)
{
Addition obj = new Addition();
Scanner value=new Scanner (System.in);
int x,y,z;
System.out.println("Enter 3 numbers:");
x=value.nextInt();
y=value.nextInt();
z=value.nextInt();
obj.sum (x,y);

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 4


obj.sum(x,y,z);
}
}
EXAMPLE:
A Java program to read MPESA account initial balance and amount to transfer. The
program then computes the charges (2% of amount to be transferred), compute all
deductions and display account final balance.
import java.util.Scanner;
public class WAINAINA
{
void MPESA(float account)
{
float money=account;
System.out.println("Your account initial state= : " +money);
}
void MPESA(float account,float pesa,float charges)
{
float money=account;
float payment=pesa*charges;
float balance=money-(pesa+(pesa*charges));
System.out.println("Charges=:" +payment);
System.out.println("Balance in account=:"+balance);
}
public static void main(String[] args)
{
WAINAINA client = new WAINAINA();
Scanner transaction=new Scanner(System.in);
float mymoney,send;
System.out.println("Your MPESA balance currently is=");
mymoney=transaction.nextFloat();
System.out.println("How much do you want to send=");
send=transaction.nextFloat();
client.MPESA(mymoney);
client.MPESA(mymoney,send, (float) 0.02);
}
}

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 5


OUTPUT:

2. By changing the data type

In this type of overloading, we define two or more functions with same name and same
number of parameters, but the type of parameter is different.

public class Addition


{
void sum(int a, int b)
{
int c = a+b;
System.out.println(" Addition of two numbers : " +c);
}
void sum(double a, double b)
{
double c = a+b;
System.out.printf("Addition of three numbers=%.2f \n:",c);
}
public static void main(String[] args)
{
Addition obj = new Addition();
obj.sum ( 30,90);

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 6


obj.sum(45.4,78.4);
}
}
3. By changing the Order of the parameters

In this type of overloading, we define two or more functions By changing the Order of the
Parameters.

import java.io.*; // * on the end means you're importing everything in the Java.IO Package.

class ZETECH
{
// Method 1
public void getunit(String name,int code)
{
// Printing unit name and unit code
System.out.println("Unit name: - " + name +"-Unit code"+code);
}
// Method 2
public void getunit(int code, String name)
{
// Again printing unit name and unit code
System.out.println("Unit name - " + name +"- Unit code"+code);
}
public static void main(String[] args)
{
// Creating object of above class
ZETECH ict = new ZETECH();
// Passing name and id
// Note: Reversing order
ict.getunit("Programming", 110);
ict.getunit(124, "Data Structures");
}
}

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 7


Important Points

1) Two or more methods can have the same name inside the same class if they accept different
arguments. This feature is known as method overloading.
2) It is not method overloading if we only change the return type of methods. There must be
differences in the number of parameters.

Implementation of Run time polymorphism (Method Overriding)

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of Method Overriding in Java

class ZETECH
{
//defining a method
void course()
{
System.out.println("My course at zetech is ICT");
}
}
//Creating a child class

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 8


class DEPARTMENT extends ZETECH
{
//defining the same method as in the parent class
void course()
{
System.out.println("My course in the department is ICT");
}

public static void main(String args[])


{
DEPARTMENT student = new DEPARTMENT();//creating object
student.course();//calling method
}
}

Overriding is done by using a reference variable of the superclass. The method to be called is
determined based on the object which is being referred to by the reference variable. This is also
known as Upcasting.

Upcasting takes place when the Parent class’s reference variable refers to the object of the child
class. For example:

Example of Method Overriding in Java using upcasting

class PROGRAMMING
{
void writecode()
{
System.out.println("OOP2 languages include Java and Python.");
}
}

class OOP extends PROGRAMMING


{
//Override
void writecode()
{

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 9


System.out.println("I like programming in OOP.");
}

public static void main(String[] args) {


OOP program = new OOP(); // Upcasting
program.writecode(); // Calls the overridden method in OOP Class
}
}

OUTPUT:

Compile-Time Polymorphism vs. Run-Time Polymorphism

Compile-Time Polymorphism Run-Time Polymorphism

• The compiler cannot control the method


• The method call is handled by the compiler
call in run-time

• Compile-Time Polymorphism is less flexible, • Run-Time Polymorphism exhibits higher


as it needs to handle all method calls in flexibility as the method calls get handled
compile-time at run-time

• The execution period for the Compile-Time • The execution period for the Run-Time
Polymorphism is less Polymorphism is more

• Integrating the right method call with the • Combining the correct method call with
proper method is done in compile-time the right method is done in run-time

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 10


• Occurs during Method Overloading and
• Occurs during Method Overriding
Operator Overloading

Super Keyword
The term "super" is a keyword in Java that refers to the program's immediate parent class object or
method. In this procedure, whenever you create an instance of a subclass, automatically, the compiler
will create an instance of the parent class implicitly. The super reference variable will be referring to
the parent class’ instance.

Example: (Declare two variables with same name but user super keyword to reference base
class variable).

class ICT_DEGREE
{
int fee_per_sem = 60650;
}
class ICT_DIP extends ICT_DEGREE
{
int fee_per_sem = 30650;
public void fees()
{
System.out.println("Fee payable for Diploma per semester: " + fee_per_sem);
System.out.println("Fee payable for Degree per semester:" + super.fee_per_sem);
}
public static void main(String[] args)
{
ICT_DIP student = new ICT_DIP();
student.fees();
}
}
OUTPUT:

GEORGE WAINAINA 0718313173/0731919231 [email protected] Page 11

You might also like