Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

03 Java Polymorphism

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

03 Java Polymorphism

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 92

JAVA ENTERPRISE EDITION

PROGRAMMING
SUBJECT DESCRIPTION: JAVA ENTERPRISE EDITION PROGRAMMING
SUBJECT CODE: CS220

ENGR. RUELLA YARES MAGTAAS, CPE


JAVA POLYMORPHISM
POLYMORPHISM IN JAVA

• Polymorphism in Java is a concept by which we can perform a single


action in different ways. Polymorphism is derived from 2 Greek words: poly
and morphs. The word "poly" means many and "morphs" means forms. So,
polymorphism means many forms.
• There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
• If you overload a static method in Java, it is the example of compile time
polymorphism.
METHOD OVERLOADING IN JAVA

• If a class has multiple methods having same name but


different in parameters, it is known as Method Overloading.
• If we have to perform only one operation, having same name
of the methods increases the readability of the program.
ADVANTAGE OF METHOD OVERLOADING

• Method overloading increases the readability of the program.


DIFFERENT WAYS TO OVERLOAD THE
METHOD

There are two ways to overload the method in java


Note:
Compile Time Error
is better than Run
• By changing number of arguments Time Error. So, java
compiler renders
• By changing the data type compiler time error
if you declare the
same method
having same
parameters.
Note
In Java, Method Overloading is not possible by
changing the return type of the method only.
1) METHOD OVERLOADING: CHANGING
NO. OF ARGUMENTS
In this example, we have created two methods,
first add() method performs addition of two numbers and
second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
2) METHOD OVERLOADING: CHANGING
DATA TYPE OF ARGUMENTS
In this example, we have created two methods that differs in data type.

The first add method receives two integer arguments and


second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b)
{return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
METHOD OVERLOADING AND TYPE
PROMOTION
One type is promoted to another
implicitly if no matching datatype is
found.

As displayed in the diagram, byte can


be promoted to short, int, long, float or
double. The short datatype can be
promoted to int, long, float or double.
The char datatype can be promoted to
int, long, float or double and so on.
METHOD OVERRIDING IN JAVA

• 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

• Method overriding is used to provide the specific


implementation of a method which is already provided by its
superclass.
• Method overriding is used for runtime polymorphism
RULES FOR JAVA METHOD OVERRIDING

• The method must have the


same name as in the parent
class
• The method must have the
same parameter as in the
parent class.
• There must be an IS-A
relationship (inheritance).
UNDERSTANDING THE PROBLEM
WITHOUT METHOD OVERRIDING
//Java Program to demonstrate why we need method overriding Problem is
//Here, we are calling the method of parent class with child that We
//class object. have to
//Creating a parent class provide a
class Vehicle{ specific
void run(){System.out.println("Vehicle is running");} implementa
} tion of run()
//Creating a child class method in
class Bike extends Vehicle{ subclass
public static void main(String args[]){ that is why
//creating an instance of child class we use
Bike obj = new Bike(); method
//calling the method with child class instance overriding.
obj.run();
}
}
EXAMPLE OF METHOD OVERRIDING
In this example, we have defined the run method in the subclass as defined in the parent
class but it has some specific implementation.
The name and parameter of the method are the same, and there is IS-A relationship
between the classes, so there is method overriding.
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class Java method
class Bike2 extends Vehicle{ overriding is
//defining the same method as in the parent class
mostly used in
void run(){System.out.println("Bike is running safely");}
Runtime
public static void main(String args[]){ Polymorphism
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
FAQ

Can we override static method?


• No, a static method cannot be overridden. It can be proved by runtime polymorphism, so
we will learn it later.

Why can we not override static method?


• It is because the static method is bound with class whereas instance method is bound with
an object. Static belongs to the class area, and an instance belongs to the heap area.

Can we override java main method?


• No, because the main is a static method.
COVARIANT RETURN TYPE

The covariant return type specifies that the return type may
vary in the same direction as the subclass.

Before Java5, it was not possible to override any


method by changing the return type. But now,
since Java5, it is possible to override method by
changing the return type if subclass overrides any
method whose return type is Non-Primitive but it
changes its return type to subclass type.
ADVANTAGES OF COVARIANT RETURN
TYPE
Following are the advantages of the covariant return type.

1) Covariant return type assists to stay away from the confusing type casts in the class
hierarchy and makes the code more usable, readable, and maintainable.

2) In the method overriding, the covariant return type provides the liberty to have more to
the point return types.

3) Covariant return type helps in preventing the run-time ClassCastExceptions on returns.


class A1 // A3 is the child class of A2
{ class A3 extends A2
A1 foo() {
{ @Override
return this; A3 foo()
} {
void print() return this;
{ }
System.out.println("Inside the class A1") @Override
; void print()
} {
} System.out.println("Inside the class A3")
;
// A2 is the child class of A1 }
class A2 extends A1 }
{
@Override public class CovariantExample
A2 foo() {
{ // main method
return this; public static void main(String argvs[])
} {
void print() A1 a1 = new A1();
{ a1.foo().print();
System.out.println("Inside the class A2")
; A2 a2 = new A2();
} a2.foo().print();
}
A3 a3 = new A3();
a3.foo().print();
}
}
HOW IS COVARIANT RETURN TYPES
IMPLEMENTED?

Java doesn't allow the return type-based overloading, but Java


Virtual Machine (JVM) always allows return type-based
overloading.
JVM uses the full signature of a method for lookup/resolution.
Full signature means it includes return type in addition to
argument types.
i.e., a class can have two or more methods differing only by
return type.
javac uses this fact to implement covariant return types.
SUPER KEYWORD IN JAVA

The super keyword in Java is a reference variable which is


used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of


parent class is created implicitly which is referred by super
reference variable.
USAGE OF JAVA SUPER KEYWORD

1. super can be used to refer


immediate parent class
instance variable.
2. super can be used to invoke
immediate parent class method.
3. super() can be used to invoke
immediate parent class
constructor.
1) SUPER IS USED TO REFER IMMEDIATE
PARENT CLASS INSTANCE VARIABLE.
We can use super keyword to access the data member or field of parent
class.
It is used if parent class and child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);// In the example,
prints color of Animal class Animal and Dog both
} classes have a
common property
}
color. If we print color
class TestSuper1{ property, it will print
public static void main(String args[]){ the color of current
Dog d=new Dog(); class by default. To
d.printColor(); access the parent
2) SUPER CAN BE USED TO INVOKE
PARENT CLASS METHOD
The super keyword can also be used to invoke parent class method.
It should be used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.
class Animal{ In the example
void eat(){System.out.println("eating...");} Animal and Dog both
} classes have eat()
class Dog extends Animal{ method if we call eat()
void eat(){System.out.println("eating bread...");} method from Dog
void bark(){System.out.println("barking...");} class, it will call the
void work(){ eat() method of Dog
super.eat(); class by default
bark(); because priority is
} given to local.
}
class TestSuper2{ To call the parent
public static void main(String args[]){ class method, we
Dog d=new Dog(); need to use super
d.work(); keyword.
}}
3) SUPER IS USED TO INVOKE PARENT
CLASS CONSTRUCTOR.
The super keyword can also be used to invoke the parent
class constructor
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){ Note: super() is
super(); added in each
System.out.println("dog is created"); class constructor
} automatically by
} compiler if there is
class TestSuper3{ no super() or
public static void main(String args[]){ this().
Dog d=new Dog();
}}
INSTANCE INITIALIZER BLOCK

Instance Initializer block is used to initialize the instance data


member. It run each time when object of the class is created.
The initialization of the instance variable can be done directly
but there can be performed extra operations while initializing
the instance variable in the instance initializer block.
FAQ

• What is the use of instance initializer block while we can directly


assign a value in instance data member?
For example:class Bike{
int speed=100
;
• }
Why use instance initializer block?
Suppose I have to perform some operations while assigning value to
instance data member e.g. a for loop to fill a complex array or error
handling etc.
EXAMPLE OF INSTANCE INITIALIZER
BLOCK
class Bike7{
int speed;

Bike7()
{System.out.println("speed is "+speed);}

{speed=100;}

public static void main(String args[]){


Bike7 b1=new Bike7();
Bike7 b2=new Bike7();
}
}
THERE ARE THREE PLACES IN JAVA
WHERE YOU CAN PERFORM OPERATIONS:

1. method
2. constructor
3. block
WHAT IS INVOKED FIRST, INSTANCE
INITIALIZER BLOCK OR CONSTRUCTOR?
class Bike8{
int speed; In the example, it
seems that instance
Bike8(){System.out.println("constructor is invoked");} initializer block is
firstly invoked but NO.
{System.out.println("instance initializer block invoked"); Instance initializer
} block is invoked at
the time of object
public static void main(String args[]){ creation. The java
Bike8 b1=new Bike8(); compiler copies the
Bike8 b2=new Bike8(); instance initializer
} block in the
} constructor after the
first statement
super(). So firstly,
constructor is
Note: The java compiler copies the code of instance
invoked. initializer block in
RULES FOR INSTANCE INITIALIZER
BLOCK :
There are mainly three rules for the instance
initializer block. They are as follows:

1. The instance initializer block is created when instance of the


class is created.
2. The instance initializer block is invoked after the parent
class constructor is invoked (i.e. after super() constructor
call).
3. The instance initializer block comes in the order in which
they appear.
PROGRAM OF INSTANCE INITIALIZER
BLOCK THAT IS INVOKED AFTER SUPER()
class A{
A(){
System.out.println("parent class constructor invoked");
}
}
class B2 extends A{
B2(){
super();
System.out.println("child class constructor invoked");
}

{System.out.println("instance initializer block is invoked");


}

public static void main(String args[]){


B2 b=new B2();
}
FINAL KEYWORD IN JAVA

The final keyword in java is used to restrict the user. The java
final keyword can be used in many context.
Final can be:

• variable
• method
• class
JAVA FINAL VARIABLE

• The final keyword can be applied with the variables, a final variable
that have no value it is called blank final variable or uninitialized final
variable.

• It can be initialized in the constructor only.

• The blank final variable can be static also which will be initialized in
the static block only.
Example of final variable
There is a final
class Bike9{ variable
final int speedlimit=90;//final variable speedlimit, we are
void run(){ going to change
speedlimit=400; the value of this
} variable, but It
public static void main(String args[]){ can't be changed
Bike9 obj=new Bike9(); because final
obj.run(); variable once
} assigned a value
}//end of class can never be
changed.
If you make any variable as final, you cannot
change the value of final variable(It will be
constant).
STATIC BLANK FINAL VARIABLE

• A static final variable that is not initialized at the time of


declaration is known as static blank final variable. It can be
initialized only in static block.

class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
JAVA FINAL METHOD

Example of final method


class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run()
{System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
If you make any method as final, you cannot
JAVA FINAL CLASS

Example of final class


final class Bike{}

class Honda1 extends Bike{


void run()
{System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

If you make any class as final, you cannot extend


FAQ

• Is final method inherited?


Yes, final method is inherited but you cannot override it.
class Bike{
final void run()
{System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
FAQ

• What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.
If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an employee.
It can be initialized only in constructor.

class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
FAQ

• Can we initialize blank final variable?


Yes, but only in constructor.
class Bike10{
final int speedlimit;//blank final variable

Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[]){


new Bike10();
}
}
FAQ

• What is final parameter?


If you declare any parameter as final, you cannot change the
value of it. class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}
FAQ

• Can we declare a constructor final?


No, because constructor is never inherited.
RUNTIME POLYMORPHISM IN JAVA

• Runtime polymorphism or Dynamic Method Dispatch is a


process in which a call to an overridden method is resolved at
runtime rather than compile-time.
• In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called
is based on the object being referred to by the reference variable.
UPCASTING

• If the reference variable of Parent class refers to the object of


Child class, it is known as upcasting.
• For upcasting, we can use the reference variable of class type
or an interface type.
EXAMPLE OF JAVA RUNTIME
POLYMORPHISM
• In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class
and overrides its run() method. We are calling the run method by the reference variable of Parent
class. Since it refers to the subclass object and subclass method overrides the Parent class
method, the subclass method is invoked at runtime.
• Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
JAVA RUNTIME POLYMORPHISM EXAMPLE:
BANK
• Consider a scenario where Bank is a class that provides a method to get the rate of
interest. However, the rate of interest may differ according to banks. For example, SBI,
ICICI, and AXIS banks are providing 8.4%, 7.3%, and 9.7% rate of interest.
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
This example
class AXIS extends Bank{ is also given
float getRateOfInterest(){return 9.7f;}
} in method
class TestPolymorphism{
public static void main(String args[]){ overriding but
Bank b;
b=new SBI();
there was no
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); upcasting.
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest())
;
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest())
;
}
JAVA RUNTIME POLYMORPHISM EXAMPLE:
SHAPEclass Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
JAVA RUNTIME POLYMORPHISM EXAMPLE:
ANIMAL
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
}
class Cat extends Animal{
void eat(){System.out.println("eating rat...");}
}
class Lion extends Animal{
void eat(){System.out.println("eating meat...");}
}
class TestPolymorphism3{
public static void main(String[] args){
Animal a;
a=new Dog();
a.eat();
a=new Cat();
a.eat();
a=new Lion();
a.eat();
}}
JAVA RUNTIME POLYMORPHISM WITH DATA
MEMBER

• A method is overridden, not the data members, so runtime


polymorphism can't be achieved by data members.
• In the example given below, both the classes have a data member speedlimit. We
are accessing the data member by the reference variable of Parent class which
refers to the subclass object. Since we are accessing the data member which is not
overridden,
class Bike{ hence it will access the data member of the Parent class always.
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;

public static void main(String args[]){


Bike obj=new Honda3();
System.out.println(obj.speedlimit);
}

Runtime polymorphism can't be achieved by data members


JAVA RUNTIME POLYMORPHISM WITH
MULTILEVEL INHERITANCE
Let's see the simple example of Runtime
Polymorphism with multilevel inheritance.
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
STATIC BINDING AND DYNAMIC BINDING

• Connecting a method call to the


method body is known as
binding.
• There are two types of binding
1.Static Binding (also known
as Early Binding).
2.Dynamic Binding (also
known as Late Binding).
UNDERSTAND THE TYPE OF INSTANCE.

1) variables have a type


Each variable has a type, it may be primitive and non-
primitive.
Here data variable is a type of int.
2) References have a type
3) Objects have a type
An object is an instance of particular java class,but it is also an instance of
its superclass.
Here d1 is an instance of Dog class, but it is also
an instance of Animal.
STATIC BINDING

When type of the object is determined at compiled time(by the


compiler), it is known as static binding.
If there is any private, final or static method in a class, there is
static binding.
DYNAMIC BINDING

When type of the object is determined at run-time, it is known


as dynamic binding.
• In the example object type cannot be determined by the compiler, because the instance of
Dog is also an instance of Animal. So, compiler doesn't know its type, only its base type.
JAVA INSTANCEOF

The java instanceof operator is used to test whether the object is


an instance of the specified type (class or subclass or interface).
The instanceof in java is also known as type comparison
operator because it compares the instance with type. It returns
either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
SIMPLE EXAMPLE OF JAVA INSTANCEOF
An object of subclass type is also a type of parent
class. For example, if Dog extends Animal then
object of Dog can be referred by either Dog or
Animal class.

Another example of java instanceof operator


instanceof in java with a variable that have null
value

If we apply instanceof operator with a variable that


have null value, it returns false. Let's see the
example given below where we apply instanceof
operator with the variable that have null value.
DOWNCASTING WITH JAVA INSTANCEOF
OPERATOR
When Subclass type refers to the object of Parent class, it is known as downcasting.
If we perform it directly, compiler gives Compilation error. If you perform it by
typecasting, ClassCastException is thrown at runtime. But if we use instanceof
operator, downcasting is possible.

If we perform downcasting by typecasting, ClassCastException is thrown at runtime.


Possibility of downcasting with instanceof
Let's see the example, where downcasting is possible by instanceof operator.
Downcasting without the use of java instanceof

Downcasting can also be performed without the use of instanceof operator as


displayed in the following example:

Let's take closer look at this, actual object that is


referred by a, is an object of Dog class. So if we
downcast it, it is fine. But what will happen if we
write:
Understanding Real use of instanceof in java

Let's see the real use of instanceof keyword by the example given below.

You might also like