Inheritance and Polymorphism: Object Oriented Programming
Inheritance and Polymorphism: Object Oriented Programming
Aneeta Siddiqui
Inheritance
The idea behind inheritance is that you can create new classes
that are built upon existing classes.
3
Inheritance
4
Inheritance
5
Inheritance
Following is the syntax of extends keyword.
class Super { public class A {
..... .....
..... .....
} }
class Sub extends Super { public class B extends A {
..... .....
..... .....
} }
6
Inheritance
For example,
class Animal {
// eat() method
// sleep() method
}
class Dog extends Animal {
// bark() method
}
7
Inheritance
8
Inheritance
IS-A Relationship
Orange is a fruit.
A surgeon is a doctor.
A dog is an animal.
9
Inheritance ( Example 1 )
class Animal {
public void eat() {
System.out.println("I can eat");
}
public void sleep() {
System.out.println("I can sleep");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("I can bark");
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.eat();
dog1.sleep();
dog1.bark();
}
}
10
Inheritance
11
Using Protected ( Example 2 )
class Animal {
protected String type;
private String color;
public void eat() {
System.out.println("I can eat");
}
public void sleep() {
System.out.println("I can sleep");
}
public String getColor(){
return color;
}
public void setColor(String col){
color = col;
}
}
12
Using Protected ( Example 2 )
class Dog extends Animal {
public void displayInfo(String c){
System.out.println("I am a " + type);
System.out.println("My color is " + c);
}
public void bark() {
System.out.println("I can bark");
}
}
13
Using Protected ( Example 2 )
class Main {
public static void main(String[] args) {
dog1.type = "mammal";
dog1.setColor("black");
dog1.displayInfo(dog1.getColor());
}
}
14
Using Protected ( Example 2 )
Output
I can eat
I can sleep
I can bark
I am a mammal
My color is black
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display brand attribute value (from the Vehicle class) and the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
16
Inheritance ( Example 3 )
Output
Tuut, Tuut!
Honda City
17
Inheritance ( Example 4 )
class Employee{
int salary = 40000;
}
class Programmer extends Employee{
int bonus = 10000;
public static void main(String args[]){
Programmer p = new Programmer();
System.out.println ("Programmer salary is: "+p.salary);
System.out.println ("Bonus of Programmer is:"+p.bonus);
}
}
18
Inheritance ( Example 4 )
Output:
Programmer salary is: 40000
Bonus of programmer is: 10000
19
Inheritance ( Example 5 )
20
Inheritance ( Example 5 )
class Calculation {
int z;
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
public void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
23
Inheritance ( Example 5 )
24
The final Keyword
If you don't want other classes to inherit from a class,
use the final keyword:
If you try to access a final class, Java will generate an error:
final class Vehicle {
... }
class Car extends Vehicle {
...
}
The output will be something like this:
Car.java:8: error: cannot inherit from final Vehicle
class Car extends Vehicle {
^
1 error
25
Types of Inheritance
26
Types of Inheritance
Multilevel Inheritance:
In Multilevel Inheritance, one class can inherit from a derived class.
Hence, the derived class becomes the base class for the new class.
Hierarchical Inheritance:
In Hierarchical Inheritance, one class is inherited by many sub classes.
Multiple Inheritance:
In Multiple Inheritance, one class extending more than one class.
Java does not support multiple inheritance.
Hybrid Inheritance:
Hybrid inheritance is a combination of Single and Multiple inheritance.
28
Multilevel Inheritance Example
29
Multilevel Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
30
Multilevel Inheritance Example
Output:
weeping...
barking...
eating...
31
Hierarchical Inheritance Example
In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance.
32
Hierarchical Inheritance Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark(); //Error
}}
33
Hierarchical Inheritance Example
Output:
meowing...
eating...
34
Super Keyword
Syntax:
super.<method-name>();
35
Super Keyword
36
Super Keyword
super.variable super.method();
37
Super Keyword ( Example )
class Super_class {
int num = 20;
38
Super Keyword ( Example )
public class Sub_class extends Super_class {
int num = 10;
// display method of sub class
public void display() {
System.out.println("This is the display method of subclass");
}
39
Super Keyword ( Example )
public static void main(String args[]) {
Sub_class obj = new Sub_class();
obj.my_method();
}
}
40
Super Keyword ( Example )
Compile and execute the above code using the following
syntax.
javac Super_Demo
java Super
41
Super Keyword ( Example )
Output:
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
42
Method Overriding
If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding.
If the same method is defined in both the superclass class and the
subclass class, then the method of the subclass class overrides the
method of the superclass. This is known as method overriding .
43
Method Overriding
44
Method Overriding
45
Method Overriding ( Example 1 )
//Java Program to illustrate the use of Java Method Overriding
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");} //defining a method
}
class Bike2 extends Vehicle{ //creating a child class
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
46
Method Overriding ( Example 1 )
Output:
Bike is running safely
47
Method Overriding ( Example 2 )
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
System.out.println("Dogs can walk and run");
}
}
public class TestDog {
public static void main(String args[]) {
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
a.move(); // runs the method in Animal class
b.move(); // runs the method in Dog class
}
}
48
Method Overriding ( Example 2 )
Output:
Animals can move
Dogs can walk and run
49
Using Super Keyword
class Animal {
public void move() {
System.out.println("Animals can move");
}
}
class Dog extends Animal {
public void move() {
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
51
Using Super Keyword
Output:
I am a dog.
52
Using Super Keyword
53
Using Super Keyword
54
Using Super Keyword ( Example 2 )
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
55
Using Super Keyword ( Example 2 )
Output:
I am an animal.
I am a dog.
56
Using Super Keyword ( Example 2 )
57
Method Overriding ( Example 3 )
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
void show() { // display i and j
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() { // display k -- this overrides show() in A
System.out.println("k: " + k);
}
}
public class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
58
Method Overriding ( Example 3 )
Output:
K:3
59
Method Overriding ( Example 4 )
class CarClass
{
public int speedLimit()
{
return 100;
}
}
class Ford extends CarClass
{
public int speedLimit()
{
return 150;
}
public static void main(String args[])
{
CarClass obj = new Ford();
int num= obj.speedLimit();
System.out.println("Speed Limit is: "+num);
}
}
60
Method Overriding ( Example 4 )
Output:
Speed Limit is: 150
61
Method Overloading vs Method Overriding
62
Method Overloading vs Method Overriding
63
Method Overloading vs Method Overriding
64
Method Overloading vs Method Overriding
65
Method Overloading vs Method Overriding
66
Polymorphism
67
Polymorphism
68
Polymorphism
69
Why Polymorphism?
70
Why Polymorphism?
71
Advantages of Polymorphism
Polymorphism allows a superclass to define methods that are
common to all of its derived classes while allowing subclasses to
specify the additional implementation of some or all of those
methods.
73
Compile time Polymorphism ( Example )
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);
}
}
74
Compile time Polymorphism ( Example )
Output:
a: 10 a and b: 10,20
double a: 5.5
O/P : 30.25
75
Runtime Polymorphism ( Example 1 )
Animal.java
Horse.java
76
Runtime Polymorphism ( Example 1 )
Output:
Neigh
77
Runtime Polymorphism ( Example 2 )
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();
}}
78
Runtime Polymorphism ( Example 2 )
Output:
eating bread...
eating rat...
eating meat...
79
Knowing is not enough, we must apply.
- Bruce Lee