0% found this document useful (0 votes)
144 views80 pages

Inheritance and Polymorphism: Object Oriented Programming

The document discusses inheritance and polymorphism in object oriented programming, including defining inheritance as allowing new classes to acquire properties of parent classes, examples of single inheritance with an Animal/Dog example, and protected and private modifiers. It also covers final classes, types of inheritance like single, multilevel, and hierarchical, and notes Java does not support multiple inheritance.

Uploaded by

Angel Angel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views80 pages

Inheritance and Polymorphism: Object Oriented Programming

The document discusses inheritance and polymorphism in object oriented programming, including defining inheritance as allowing new classes to acquire properties of parent classes, examples of single inheritance with an Animal/Dog example, and protected and private modifiers. It also covers final classes, types of inheritance like single, multilevel, and hierarchical, and notes Java does not support multiple inheritance.

Uploaded by

Angel Angel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

Sir Syed University of Engineering and Technology

Computer Engineering Department

Object Oriented Programming

Inheritance and Polymorphism

Aneeta Siddiqui
Inheritance

 Object Oriented Programming allows you to define


new classes from existing classes. This is called Inheritance.

 Inheritance is a mechanism in which one object acquires all


the properties and behaviors of a parent object.

 The idea behind inheritance is that you can create new classes
that are built upon existing classes.

 When you inherit from an existing class, you can reuse


methods and fields of the parent class.
2
Why use Inheritance?

 For Method Overriding (so runtime polymorphism can be achieved).

 For Code Reusability.

3
Inheritance

Class A Parent Class / Base Class / Super Class

Class B Child Class / Derived Class / Sub Class

4
Inheritance

 The class which inherits the properties of other is known as


subclass ( derived class, child class ).

 The class whose properties are inherited is known as


superclass ( base class, parent class ).

 To inherit the properties of a class extends keyword is used.

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

 In Java, we use the extends keyword to inherit from a class.


Here, we have inherited the Dog class from the Animal class.

 The Animal is the superclass (parent class or base class), and


the Dog is a subclass (child class or derived class).
The subclass inherits the fields and methods of the superclass.

8
Inheritance

 IS-A Relationship

 Inheritance is an is-a relationship. We use inheritance only


if an is-a relationship is present between the two classes.

 Here are some examples:


 A car is a vehicle.

 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

 Here, we have inherited a subclass Dog from


superclass Animal. The Dog class inherits the
methods eat() and sleep() from the Animal class.

 Hence, objects of the Dog class can access the members of


both the Dog class and the Animal class.

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) {

Dog dog1 = new Dog();


dog1.eat();
dog1.sleep();
dog1.bark();

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

 Here, the type field inside the Animal class is protected.


We have accessed this field from the Main class using
dog1.type = "mammal";
 It is possible because both the Animal and Main classes are in the
same package (same file).
15
Inheritance ( Example 3 )
class Vehicle {
protected String brand = “Honda"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println ("Tuut, Tuut!");
}
}
class Car extends Vehicle {
private String modelName = “City"; // Car attribute
public static void main(String[] args) {
Car myCar = new Car(); // Create a myCar object

// 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 )

 Following is an example demonstrating Java inheritance.

 In this example, you can observe two classes namely


Calculation and My_Calculation.

 Using extends keyword, the My_Calculation inherits the


methods addition() and Subtraction() of Calculation class.

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);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
21
Inheritance ( Example 5 )
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Compile and execute the above code as shown below.


javac My_Calculation.java
java My_Calculation
22
Inheritance ( Example 5 )
 Output:
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

23
Inheritance ( Example 5 )

 In the given program, when an object


to My_Calculation class is created, a copy of the contents of
the superclass is made within it. That is why, using the object
of the subclass you can access the members of a superclass.

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

Single Inheritance Multi Level Inheritance Hierarchical Inheritance

26
Types of Inheritance

Multiple Inheritance Hybrid Inheritance

Java does not support Multiple Inheritance


27
Types of Inheritance
 Single Inheritance:
In Single Inheritance one class extends another class (one class only).

 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

 When there is a chain of inheritance, it is known as


multilevel inheritance.

 In the example given below, BabyDog class inherits the


Dog class which again inherits the Animal class, so there is a
multilevel inheritance.

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

 When two or more classes inherits a single class, it is known


as hierarchical inheritance.

 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

 The super keyword is similar to "this" keyword.

 The super keyword can be used to access any data member or


methods of the parent class.

 Super keyword can be used at variable, method and


constructor level.

 Syntax:

super.<method-name>();

35
Super Keyword

 The super keyword is similar to this keyword.

 Following are the scenarios where the super keyword is used.

1. It is used to differentiate the members of superclass from


the members of subclass, if they have same names.

2. It is used to invoke the superclass constructor from


subclass.

36
Super Keyword

 Differentiating the Members

 If a class is inheriting the properties of another class.


And if the members of the superclass have the names same as
the sub class, to differentiate these variables we use super
keyword as shown below.

super.variable super.method();

37
Super Keyword ( Example )
class Super_class {
int num = 20;

// display method of superclass


public void display() {
System.out.println("This is the display method of superclass");
}
}

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");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();
// Invoking the display() method of sub class
sub.display();

// Invoking the display() method of superclass


super.display();
// printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super class:"+ super.num);
}

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.

 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.

 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

 Usage of Java Method Overriding

1. Method overriding is used to provide the specific


implementation of a method which is already provided by
its superclass.

2. Method overriding is used for runtime polymorphism

44
Method Overriding

 Rules for Java Method Overriding

1. The method must have the same name as in the parent


class

2. The method must have the same parameter as in the parent


class.

3. There must be an IS-A relationship (inheritance).

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");
}
}

public class TestDog {


public static void main(String args[]) {
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}
50
Using Super Keyword
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


public void displayInfo() {
System.out.println("I am a dog.");
}
}

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

 In the above program, the displayInfo() method is present in


both the Animal superclass and the Dog subclass.

 When we call displayInfo() using the d1 object


(object of the subclass), the method inside the subclass Dog is
called. The displayInfo() method of the subclass overrides the
same method of the superclass.

53
Using Super Keyword

 A common question that arises while performing overriding in


Java is:

 Can we access the method of the superclass after


overriding?

 Well, the answer is Yes. To access the method of the superclass


from the subclass, we use the super keyword.

54
Using Super Keyword ( Example 2 )
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}

class Dog extends Animal {


public void displayInfo() {
super.displayInfo();
System.out.println("I am a dog.");
}
}

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 )

 In the above example, the subclass Dog overrides the


method displayInfo() of the superclass Animal.

 When we call the method displayInfo() using the d1 object of


the Dog subclass, the method inside the Dog subclass is called;
the method inside the superclass is not called.

 Inside displayInfo() of the Dog subclass, we have


used super.displayInfo() to call displayInfo() of the superclass.

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

Here speedLimit() method of class Ford is overriding


the speedLimit() method of class CarClass.

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

 Polymorphism is the capability of a method to do different


things based on the object that it is acting upon.

 In other words, polymorphism allows you define one interface


and have multiple implementations.

67
Polymorphism

 Types of polymorphism and method overloading & overriding


are covered in the separate tutorials. You can refer them here:
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)

68
Polymorphism

69
Why Polymorphism?

 With Polymorphism, it is possible to write a method that


correctly processes lots of different types of functionalities
with the same name. Polymorphism also allows gaining
consistency in our code.

70
Why Polymorphism?

 For example, suppose we need to execute the animalSound()


method of both Dog and Cat. To do so, we can create an
‘Animal’ class and extend two subclasses Dog and Cat from it.
In this case, it makes sense to create a method with the same
name animalSound() in both these subclasses rather than
creating methods with different names.

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.

 Method Overriding is supported by Dynamic Polymorphism


which is a key aspect of dynamic binding or run-time
polymorphism.

 Polymorphism provides the ability to a method to do different


things on the basis of the object upon which it is acting.
72
Compile time Polymorphism ( Example )
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);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}

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

public class Animal{


public void sound(){
System.out.println("Animal is making a sound");
}
}

Horse.java

class Horse extends Animal{


public void sound(){ //Override
System.out.println("Neigh");
}
public static void main(String args[]){
Animal obj = new Horse();
obj.sound();
}
}

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.

Willing is not enough, we must do.

- Bruce Lee

Copy protected with Online-PDF-No-Copy.com 80

You might also like