lecture 10 - Polymorphism - Amended

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Lecture 10:

Polymorphism
Method Overloading, Method Overriding, super keyword, final
keyword, Runtime Polymorphism

Object Oriented Programming


1
Introduction
• The word polymorphism means having many forms. In simple words, we
can define polymorphism as the ability of a message to be displayed in
more than one form.

• Real life example of polymorphism: A person at the same time can have
different characteristic. Like a man at the same time is a father, a
husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.

• Polymorphism is considered one of the important features of Object-


Oriented Programming. Polymorphism allows us to perform a single action
in different ways. In other words, polymorphism allows you to define one
interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.

2
Types of polymorphism
• Types of polymorphism :

1. Method Overloading in Java – This is an example of compile time (or


static polymorphism)

2. Method Overriding in Java – This is an example of runtime time (or


dynamic polymorphism)

3. Types of Polymorphism – Runtime and compile time

3
Method Overloading in Java
• Method overloading is a concept that allows to declare multiple methods with
same name but different parameters in the same class.

• Java supports method overloading and always occur in the same class(unlike
method overriding).

• Method overloading is one of the ways through which java supports polymorphism.
Polymorphism is a concept of object oriented programming that deal with multiple
forms.

• Method overloading can be done by changing number of arguments or by


changing the data type of arguments.

• If two or more method have same name and same parameter list but differs in
return type can not be overloaded.

• Note: Overloaded method can have different access modifiers and it does not have
any significance in method overloading.
4
Two ways of Method Overloading
• There are two different ways of method overloading.
1. Different datatype of arguments
2. Different number of arguments

• Method overloading by changing data type of arguments.

• Example:
• In this example, we have two sum() methods that take integer and float
type arguments respectively.

• Notice that in the same class we have two methods with same name but
different types of parameters

5
Method overloading by changing data type of
arguments.
• Method overloading by changing data type of arguments.

class Calculate
{
• Output
void sum (int a, int b)
{
– Sum is 13
System.out.println("sum is"+(a+b)) ; – Sum is 8.4
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6, 3.8); //sum(float a, float b) is called.
}
}

You can see that sum() method is overloaded two times. The first takes two
6
integer arguments, the second takes two float arguments.
Method overloading by changing no. of argument.

• In this example, we have two methods


• Output
class Demo – Result is 40
{ – Result is 48
void multiply(int l, int b)
{
System.out.println("Result is"+(l*b)) ;
}

void multiply(int l, int b, int h)


{
System.out.println("Result is"+(l*b*h));
}
public static void main(String[] args)
{
Demo ar = new Demo();
ar.multiply(8,5); //multiply(int l, int b) is method is called
ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
}
}

7
Method overloading by changing no. of argument.

• In this example the multiply() method is overloaded twice. The first method
takes two arguments and the second method takes three arguments.

• When an overloaded method is called Java look for match between the
arguments to call the method and the its parameters. This match need not
always be exact, sometime when exact match is not found, Java
automatic type conversion plays a vital role.

8
Method Overriding in Java
• Method overriding is a process of overriding base class method by derived
class method with more specific definition.

• Method overriding performs only if two classes have is-a relationship. It


mean class must have inheritance. In other words, It is performed between
two classes using inheritance relation.

• In overriding, method of both class must have same name and equal
number of parameters.

• Method overriding is also referred to as runtime polymorphism because


calling method is decided by JVM during runtime.

• The key benefit of overriding is the ability to define method that's


specific to a particular subclass type.

9
Method Overriding in Java
• Rules for Method Overriding

1. Method name must be same for both parent and child classes.

2. Access modifier of child method must not restrictive than parent class method.

3. Private, final and static methods cannot be overridden.

4. There must be an IS-A relationship between classes (inheritance).

10
Example of Method Overriding
• Below we have simple code example with one parent class and one child class
wherein the child class will override the method provided by the parent class.

class Animal
• Output
{
public void eat() Dog like to eat meat
{
System.out.println("Eat all eatables");
}
}

class Dog extends Animal


{
public void eat() //eat() method overridden by Dog class.
{
System.out.println("Dog like to eat meat");
}

public static void main(String[] args) {


Dog d = new Dog();
d.eat();
}
11
}
Example of Method Overriding
• As you can see here Dog class gives it own implementation of eat()
method. For method overriding, the method must have same name and
same type signature in both parent and child class.

• NOTE: Static methods cannot be overridden because, a static method is


bounded with class where as instance method is bounded with object.

12
Example: Access modifier is more restrictive in child
class
• Java does not allows method overriding if child class has more restricted access
modifier than parent class.
• In the below example, to the child class method, we set protected which is restricted
than public specified in parent class.

class Animal
{
public void eat() • Output:
{
System.out.println("Eat all eatables");
Cannot reduce the visibility
} of the inherited method from
} Animal.

class Dog extends Animal


{
protected void eat() //error
{
System.out.println("Dog like to eat meat");
}

public static void main(String[] args) {


Dog d = new Dog();
d.eat();
}
} 13
Runtime Polymorphism or Dynamic method
dispatch
• Dynamic method dispatch is a mechanism by which a call to an overridden
method is resolved at runtime. This is how java implements runtime
polymorphism. When an overridden method is called by a reference, java
determines which version of that method to execute based on the type of
object it refer to. In simple words the type of object which it referred
determines which version of overridden method will be called.

14
Upcasting in Java
• If the reference variable of Parent class refers to the object of Child class,
it is known as upcasting.

• When Parent class reference variable refers to Child class object, it is


known as Upcasting. In Java this can be done and is helpful in scenarios
where multiple child classes extends one parent class. In those cases we
can create a parent class reference and assign child class objects to it.

• For example:

class A{

}
class B extends A{
A a=new B();//upcasting

15
Java Runtime Polymorphism Example: Shape
class Shape{
void draw()
{System.out.println("drawing..."); }
}
class Rectangle extends Shape{
void draw()
{System.out.println("drawing rectangle...");}
}
class Circle extends Shape{
• Output:
void draw() drawing rectangle...
{System.out.println("drawing circle...");} drawing circle...
}
drawing triangle...
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();
} 16
}
Java Runtime Polymorphism Example: Animal
class Animal{
void eat()
{System.out.println("eating...");}
}
class Dog extends Animal{ • Output:
void eat()
eating bread...
{System.out.println("eating bread...");}
} eating rat...
class Cat extends Animal{ eating meat...
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();
17
}}
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");}
} • Output:
class Dog extends Animal{
eating
void eat()
{System.out.println("eating fruits");}
eating fruits
} drinking Milk
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(); 18
}
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


– super can be used to refer immediate parent class instance variable.
– super can be used to invoke immediate parent class method.
– super() can be used to invoke immediate parent class constructor.

19
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(){
• Output:
System.out.println(color);//prints color of Dog class – black
System.out.println(super.color);//prints color of Animal class – white
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
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. 20
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.

• In the below 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, we need to use super keyword.

21
2) super can be used to invoke parent class
method
class Animal{
void eat(){
System.out.println("eating...");
} }
class Dog extends Animal{
void eat(){
• Output:
System.out.println("eating bread...");
}
– eating...
void bark(){ – barking...
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}

22
3) super is used to invoke parent class
constructor.
• The super keyword can also be used to invoke the parent class
constructor. Let's see a simple example:

class Animal{
Animal() { • Output:
System.out.println("animal is created"); – animal is created
} – dog is created
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}
}

23
super example: real use
• 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.

24
super example: real use
class Person{
int id;
String name;
Person(int id,String name){
this.id=id;
this.name=name;
}
}
• Output:
class Emp extends Person{
float salary;
– 1 Bruno 45000
Emp(int id,String name,float salary){
super(id,name);//reusing parent constructor
this.salary=salary;
}
void display(){
System.out.println(id+" "+name+" "+salary);}
}

class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"Bruno",45000f);
e1.display(); 25
}}
Final Keyword In Java
• Final modifier is used to declare a field as final. It can be used with
variable, method or a class.
• If we declare a variable as final then it prevents its content from being
modified. The variable acts like a constant. Final field must be initialized
when it is declared.

• If we declare a method as final then it prevents it from being overridden.


• If we declare a class as final then it prevents from being inherited. We can
not inherit final class 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

26
Example: Final variable
• In this example, we declared a final variable and later on trying to modify
its value. But final variable can not be reassigned so we get compile time
error.

public class Test {

final int a = 10;


public static void main(String[] args) {
Test test = new Test();
test.a = 15; // compile error

System.out.println("a = "+test.a);
}
}

• Output
error: The final field Test.a cannot be assigned
27
Example: Final Method
• A method which is declared using final keyword known as final method. It is useful
when we want to prevent a method from overridden.
• In this example, we are creating a final method learn() and trying to override it but
due to final keyword compiler reports an error.

class StudyTonight
{
final void learn()
{
System.out.println("learning something new"); • Output
} – Cannot override the final method
} from StudyTonight
// concept of Inheritance
class Student extends StudyTonight • This will give a compile time error
{ because the method is declared
void learn()
as final and thus, it cannot be
{
System.out.println("learning something interesting");
overridden.
}

public static void main(String args[]) {


Student object= new Student();
object.learn();
} 28
}
Final Class
• A class can also be declared as final. A class declared as final cannot be
inherited. The String class in java.lang package is an example of a final
class.

• We can create our own final class so that no other class can inherit it.

• Example: Final Class


• In this example, we created a final class ABC and trying to extend it from
Demo class. but due to restrictions compiler reports an error. See the
below example.

29
Final Class
final class ABC{

int a = 10;
void show() {
System.out.println("a = "+a);
}
}

public class Demo extends ABC{

public static void main(String[] args) {

Demo d = new Demo();


}
}

• Output
– The type Demo cannot subclass the final class ABC
30

You might also like