Module 8
Module 8
Chapter 8
OOP Polymorphism
Introduction
Learning Outcomes:
Suppose you have to perform addition of the given numbers but there
can be any number of arguments, if you write the method such as a(int,int)
for two parameters, and b(int,int,int) for three parameters then it may be
difficult for you as well as other programmers to understand the behavior of
the method because its name differs.
NOTE: Method Overloading is not possible by changing the return type of the
method only.
1. 1. class Adder{
2. 2. static int add(int a,int b){return a+b;}
3. 3. static int add(int a,int b,int c) Output of the
{return a+b+c;} Program:
4. 4. }
22
5. 5. class TestOverloading1{
33
6. 6. public static void main(String[] args){
7. 7. System.out.println(Adder.add(11,11));
8. 8. System.out.println(Adder.add(11,11,11));
9. 9. }}
1. 1. class Adder{
2. 2. static int add(int a, int b){return a+b;}
3. 3. static double add(double a, double b)
{return a+b;} Output of the
4. 4. } Program:
5. 5. class TestOverloading2{
22
6. 6. public static void main(String[] args){ 24.9
7. 7. System.out.println(Adder.add(11,11));
8. 8. System.out.println(Adder.add(12.3,12.6));
9. 9. }}
QUESTION: Why Method Overloading is not possible by changing the return type
of method only?
ANSWER: In java, method overloading is not possible by changing the return
type of the method only because of ambiguity.
Object-Oriented Programming
Example:
1. 1. class Adder{
2. 2. static int add(int a,int b){return a+b;}
3. 3. static double add(int a,int b){return a+b;}
4. 4. }
5. 5. class TestOverloading3{
6. 6. public static void main(String[] args){
7. 7. System.out.println(Adder.add(11,11));//ambiguity
8. 8. }}
1. 1. class TestOverloading4{
2. 2. public static void main(String[] args)
{System.out.println("main with String[]");}
3. 3. public static void main(String args)
{System.out.println("main with String");}
4. 4. public static void main(){System.out.println("main without args");}
Output of the
Program:
Example:
1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
1. 3. void sum(int a,int b,int c){System.out.println(a+b+c);}
2. 4.
3. 5. public static void main(String args[]){
4. 6. OverloadingCalculation1 obj=new OverloadingCalculation1();
5. 7. obj.sum(20,20);//now second int literal will be promoted to long
6. 8. obj.sum(20,20,20);
7. 9.
8. 10. }
11. }
Output of the
Program:
40
60
Method Overloading with Type Promotion if matching found
1. class OverloadingCalculation2{
1. 2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b)
{System.out.println("long arg method invoked");}
2. 4.
5. public static void main(String args[]){
3. 6. OverloadingCalculation2 obj=new OverloadingCalculation2();
Object-Oriented Programming
Output of the
Program:
ASSESSMENT TASK
package com.journaldev.methodoverloading;
public class TypePromotionExample {
void add(float dataOne, float dataTwo) {
System.out.println(dataOne + dataTwo
+ " type float"); Output of the
} Program:
void add(long dataOne, long dataTwo) {
System.out.println(dataOne + dataTwo
+ " type long");
}
public static void main(String[] args) {
TypePromotionExample tpe = new
TypePromotionExample();
tpe.add(5, 5);
}
}
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.
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).
1.
//Java Program to demonstrate why method overriding is
needed
2.
//Here, we are calling the method of parent class with chi
ld
3. //class object.
4. //Creating a parent class Output of the
Program:
5. class Vehicle{
6. void run(){System.out.println("Vehicle is running");} Vehicle is running
7. }
8. //Creating a child class
9. class Bike extends Vehicle{
10. public static void main(String args[]){
11. //creating an instance of child class
12. Bike obj = new Bike();
13. //calling the method with child class instance
14. obj.run();
15. }
Problem is that it is needed to provide a specific implementation of
16. }method in subclass that is why method overriding is used.
run()
1.
//Java Program to illustrate the use of Java Method Overri
ding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
Object-Oriented Programming
Output of the
Program:
Bike is running
safely
1.
//Java Program to demonstrate the real scenario of Java Method Over
riding
2. //where three classes are overriding the method of a parent class.
3. //Creating a parent class.
4. class Bank{
5. int getRateOfInterest(){return 0;}
6. }
7. //Creating child classes.
8. class SBI extends Bank{ Output of the
9. int getRateOfInterest(){return 8;} Program:
10. } SBI Rate of Interest: 8
ICICI Rate of Interest: 7
11. class ICICI extends Bank{
AXIS Rate of Interest: 9
12. int getRateOfInterest(){return 7;}
13. }
14. class AXIS extends Bank{
Object-Oriented Programming
ASSESSMENT TASK
class Human{
public void eat()
{
System.out.println("Human is eating");
} Output of the
} Program:
class Boy extends Human{
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
obj.eat();
}
}
Object-Oriented Programming
class MyBaseClass{
protected void disp()
{
System.out.println("Parent class
method"); Output of the
} Program:
}
class MyChildClass extends MyBaseClass{
public void disp(){
System.out.println("Child class
method");
}
public static void main( String args[]) {
MyChildClass obj = new MyChildClass();
obj.disp();
}
}
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.
Object-Oriented Programming
Example:
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){ Output of the
Program:
7. System.out.println(color);//prints color of Dog class
8. black
System.out.println(super.color);//prints color of Animalclas white
s
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
In the above example, Animal and Dog both classes have a common
property color. If we print color property, it will print the color of current class
by default. To access the parent property, we need to use super keyword.
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.
Example:
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");} Output of the
7. void work(){ Program:
8. super.eat(); eating…
9. bark(); barking…
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
Object-Oriented Programming
In the above example Animal and Dog both classes have eat() method
if we call eat() method from Dog class, it will call the eat() method of Dog
class by default because priority is given to local. To call the parent class
method, use the super keyword.
Example 1:
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
Output of the
5. Dog(){ Program:
6. super();
7. System.out.println("dog is created"); animal is created
dog is created
8. }
9. }
10. class TestSuper3{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }}
NOTE: super() is added in each class constructor automatically by compiler if
there is no super() or this().
Let's see the real use of super keyword. Here, Emp class inherits
Person class so all the properties of Person will be inherited to Emp by
default. To initialize all the property, we are using parent class constructor
from child class. In such way, we are reusing the parent class constructor.
Example 2:
1. class Person{
2. int id;
3. String name;
4. Person(int id,String name){
5. this.id=id;
6. this.name=name; Output of the
Program:
7. }
8. } 1 ankit 45000
9. class Emp extends Person{
10. float salary;
11. Emp(int id,String name,float salary){
12. super(id,name);//reusing parent constructor
13. this.salary=salary;
Object-Oriented Programming
ASSESSMENT TASK
class Superclass
{
int num = 100;
}
class Subclass extends Superclass
{ Output of the
int num = 110; Program:
void printNumber(){
System.out.println(num);
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.printNumber();
}
}
class Animal {
public void animalSound() {
System.out.println("The animal makes a
sound");
}
}
class Dog extends Animal {
public void animalSound() {
Object-Oriented Programming
Output of the
Program:
Final Keyword
1. Final variable
2. Final method
3. Final class
4. Is final method inherited?
The final keyword in java is used to restrict the user. The java final
keyword can be used in many contexts. Final can be:
variable
method
class
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.
Object-Oriented Programming
1. Final variable. If you make any variable as final, you cannot change
the value of final variable (It will be constant).
Example:
There is a final variable speedlimit, we are going to change the value
of this variable, but It can't be changed because final variable once assigned
a value can never be changed.
1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400; Output of the
5. } Program:
6. public static void main(String args[]){
Compile Time Error
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
2. Final method. If you make any method as final, you cannot override
it.
Example:
1. class Bike{
2. final void run(){System.out.println("running");}
3. }
4. class Honda extends Bike{
5. void run()
Output of the
{System.out.println("running safely with 100kmph"); Program:
6. }
Compile Time Error
7. public static void main(String args[]){
8. Honda honda= new Honda();
9. honda.run();
10. }
11. }
3. Final class. If you make any class as final, you cannot extend it.
Example:
Object-Oriented Programming
Example:
1. class Bike{
2. final void run(){System.out.println("running...");}
3. } Output of the
4. class Honda2 extends Bike{ Program:
5. public static void main(String args[]){ running…
6. new Honda2().run();
7. }
8. }
Object-Oriented Programming
ASSESSMENT TASK
class StudentData{
final int ROLL_NO;
StudentData(int rnum){
Output of the
ROLL_NO=rnum;
Program:
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
} Output of the
} Program:
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. Here, we will focus on runtime polymorphism in java.
Upcasting
If the reference variable of Parent class refers to the object of Child
class, it is known as upcasting. For example:
Object-Oriented Programming
Example
1. class A{}
2. class B extends A{}
1. 1. A a=new B();//upcasting
1. interface I{}
2. class A{}
3. class B extends A implements I{}
1. class Bike{
2. void run(){System.out.println("running");}
3. }
4. class Splendor extends Bike{
5. void run()
{System.out.println("running safely with 60km");}
6. public static void main(String args[]){
Object-Oriented Programming
Output of the
Program:
Note: This example is also given in method overriding but there was no
upcasting.
1. class Bank{
2. float getRateOfInterest(){return 0;}
3. }
4. class SBI extends Bank{
5. float getRateOfInterest(){return 8.4f;}
6. }
7. class ICICI extends Bank{
8. float getRateOfInterest(){return 7.3f;}
9. }
10. class AXIS extends Bank{
Output of the
11. float getRateOfInterest(){return 9.7f;} Program:
12. }
SBI Rate of Interest: 8.4
13. class TestPolymorphism{ ICICI Rate of Interest: 7.3
14. public static void main(String args[]){ AXIS Rate of Interest: 9.7
15. Bank b;
16. b=new SBI();
17.
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
Object-Oriented Programming
1. class Shape{
2. void draw(){System.out.println("drawing...");}
3. }
4. class Rectangle extends Shape{
5. void draw(){System.out.println("drawing rectangle...");}
6. }
7. class Circle extends Shape{
8. void draw(){System.out.println("drawing circle...");}
Output of the
9. } Program:
10. class Triangle extends Shape{
drawing rectangle...
11. void draw(){System.out.println("drawing triangle...");}
drawing circle...
12. } drawing triangle...
13. class TestPolymorphism2{
14. public static void main(String args[]){
15. Shape s;
16. s=new Rectangle();
17. s.draw();
18. s=new Circle();
19. s.draw();
20. s=new Triangle();
21. s.draw();
22. }
23. }
Object-Oriented Programming
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. }
7. class Cat extends Animal{
8. void eat(){System.out.println("eating rat...");} Output of the
Program:
9. }
10. class Lion extends Animal{ eating bread...
11. void eat(){System.out.println("eating meat...");} eating rat...
eating meat...
12. }
13. class TestPolymorphism3{
14. public static void main(String[] args){
15. Animal a;
16. a=new Dog();
17. a.eat();
18. a=new Cat();
19. a.eat();
20. a=new Lion();
21. a.eat();
22. }}
subclass object. Since we are accessing the data member which is not
overridden, hence it will access the data member of the Parent class always.
Rule: Runtime polymorphism can't be achieved by data members.
1. class Bike{
2. int speedlimit=90;
3. }
Output of the
4. class Honda3 extends Bike{ Program:
5. int speedlimit=150;
6. public static void main(String args[]){ 90
1. class Animal{
2. void eat(){System.out.println("eating");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating fruits");}
6. }
Output of the
7. class BabyDog extends Dog{
Program:
8. void eat(){System.out.println("drinking milk");}
9. public static void main(String args[]){ eating
eating fruits
10. Animal a1,a2,a3;
drinking Milk
11. a1=new Animal();
12. a2=new Dog();
13. a3=new BabyDog();
14. a1.eat();
15. a2.eat();
16. a3.eat();
17. }
18. }
Object-Oriented Programming
ASSESSMENT TASK
Identify the output of the following programs:
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," +
b); Output of the
} Program:
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
class Animal {
public void animalSound() {
System.out.println("The animal makes a
sound");
}
}
class Pig extends Animal {
public void animalSound() {
System.out.println("The pig says: wee wee");
} Output of the
} Program:
class Dog extends Animal {
public void animalSound() {
System.out.println("The dog says: bow wow");
}
}
Object-Oriented Programming
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.
Let's see the simple example of instance operator where it tests the current
class.
1. class Simple1{
2. public static void main(String args[]){ Output of the
Program:
3. Simple1 s=new Simple1();
4. System.out.println(s instanceof Simple1);//true true
5. }
6. }
1. class Animal{}
2. class Dog1 extends Animal{//Dog inherits Animal
3. public static void main(String args[]){ Output of the
4. Dog1 d=new Dog1(); Program:
ASSESSMENT TASK
Identify the output of the following programs:
class Animal { }
class Dog3 extends Animal {
static void method(Animal a) {
if(a instanceof Dog3){ Output of the
Dog3 d=(Dog3)a; Program:
System.out.println("ok downcasting performed");
}
}
public static void main (String [] args) {
Animal a=new Dog3();
Dog3.method(a);
}
}
Object-Oriented Programming
References:
1. https://www.programiz.com/java-programming
2. https://www.javatpoint.com
3. https://beginnersbook.com/2017
4. https://www.w3schools.com/java
5. https://www.geeksforgeeks.org
6. https://www.tutorialspoint.com/java