lecture 10 - Polymorphism - Amended
lecture 10 - Polymorphism - Amended
lecture 10 - Polymorphism - Amended
Polymorphism
Method Overloading, Method Overriding, super keyword, final
keyword, Runtime Polymorphism
• 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.
2
Types of polymorphism
• Types of polymorphism :
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.
• 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
• 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.
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.
• In overriding, method of both class must have same name and equal
number of parameters.
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.
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");
}
}
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.
14
Upcasting in Java
• If the reference variable of Parent class refers to the object of Child class,
it is known as upcasting.
• 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
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.
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.
• 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.
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.
}
• We can create our own final class so that no other class can inherit it.
29
Final Class
final class ABC{
int a = 10;
void show() {
System.out.println("a = "+a);
}
}
• Output
– The type Demo cannot subclass the final class ABC
30