You are on page 1of 37

Object Oriented Programming

Chapter - 3 : Inheritance

Compiled By Yohans Samuel(MSc)

1
Contents

INHERITANCE

1. Inheritance
2. Advantage of Inheritance
3. Inheritance Types
4. Inheritance Rules
5. Important Notes

2
Inheritance (1)
• In the real world: We inherit traits from our mother and
father.
• We also inherit traits from our grandmother, grandfather,
and ancestors.
• We might have similar eyes, the same smile, a different
height . . . but we are in many ways "derived" from our
parents.
• Inheritance in java is a mechanism in which one object
acquires all the properties and behaviors of parent object.

3
Inheritance (2)
• Inheritance is a fundamental feature of object-oriented
programming which enables the programmer to write a
class, based on an already existing class.
• The already existing class is called the parent class, or
super-class, and the new class is called the subclass, or
derived class.
• The subclass inherits (reuses) the non-private members
(methods and variables) of the super-class, and may define
its own members as well.
• Inheritance is implemented in Java using the keyword
extends.
• When class B is a subclass of class A, we say B extends A.

4
Inheritance (3)
Student GraduateStudent, UndergraduateStudent

Shape Circle, Triangle, Rectangle

Loan CarLoan, HomeImprovementLoan, MortgageLoan

Employee Admin staff, academic Staff

BankAccount CheckingAccount, SavingsAccount

5
Inheritance (4)
A subclass
• may inherit accessible data fields and methods from its
superclass (the immediate parent and all its Ancestors).
• may add new data fields and methods.
• may also override an inherited method by providing its
own version, or
• hide an inherited variable by defining a variable of the same.
• Sometimes it is necessary for the subclass to modify the
implementation of a method defined in the superclass.
• This is referred to as method overriding.

6
Inheritance (5)
What is inherited?
• When a subclass extends a superclass in Java, all protected
and public fields and methods of the superclass are
inherited by the subclass.
• By inherited is meant that these fields and methods are part
of of the subclass, as if the subclass had declared them itself.
• protected and public fields can be called and referenced just
like the methods declared directly in the subclass.
• Fields and methods with default (package) access modifiers
can be accessed by subclasses only if the subclass is located
in the same package as the superclass.

7
Inheritance (6)
• private fields and methods of the superclass can never be
referenced directly by subclasses.
– They can, however, be referenced indirectly via methods
reachable from the subclass (e.g default (package),
protected and public methods).
• Constructors are not inherited by subclasses, but a subclass
constructor must call a constructor in the superclass.
• The inheritance relationship of subclasses and super-classes
gives rise to a hierarchy.
• With the use of inheritance the information is made
manageable in a hierarchical order.

8
Inheritance (7)

Inheritance Hierarchy for Shapes


9
Inheritance (8)
• The inheritance relationship is transitive: if class x extends
class y, then a class z, which extends class x, will also inherit
from class y.
public class Animal{ …}
public class Mammal extends Animal{…}
public class Reptile extends Animal{…}
public class Dog extends Mammal{…}
• Now based on the above example, In Object Oriented terms
the following are true:
• Animal is the superclass of Mammal and Reptile classes.
• Mammal and Reptile are subclasses of Animal class.
• Dog is the subclass of both Mammal and Animal classes.
10
Inheritance (9)

11
Inheritance (10)
public class Animal { // Animal super-class
String name;
public Animal(String n) { name = n; }
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
}
12
Inheritance (11)
//Dog Subclass //Cat Subclass
public class Dog extends Animal { public class Cat extends Animal {

private int fleas; private int hairballs;

public Dog(String n, int f) { public Cat(String n, int h) {

// calls Animal constructor // calls Animal constructor

super(n); super(n);

fleas = f; hairballs = h;

} }
public int getFleas() { public int getHairballs() {
return fleas; return hairballs;

} }
public void speak() { public void speak() {
System.out.println("Woof"); System.out.println("Meow");
} }
} } 13
Syntax of Inheritance (1)
Class Subclass-name extends Superclass-name
{
//methods and fields
}
Example:
class Car extends Vehicle
{
//class contents
}
14
Syntax of Inheritance (2)
Here is an inheritance example using the extends keyword:
public class Vehicle {
protected String licensePlate = null;

public void setLicensePlate(String license) {


this.licensePlate = license;
}
}
public class Car extends Vehicle {
int numberOfSeats = 0;

public String getNumberOfSeats() {


return this.numberOfSeats;
}
}
15
Advantages of Inheritance (1)
• Code reusability:- Inheritance automates the process of reusing
the code of the super-classes in the subclasses.
– With inheritance, an object can inherit its more general properties from
its parent object, and that saves the redundancy in programming.
• Code maintenance:- Organizing code into hierarchical classes
makes its maintenance and management easier.
• Implementing OOP:- Inheritance helps to implement the basic
OOP philosophy to adapt computing to the problem and not
the other way around,
– because entities (objects) in the real world are often organized into a
hierarchy.

16
Inheritance Types (1)
• Single level inheritance:- Inheritance in which a class inherits from
only one super class.
• Multi-level inheritance:- Inheritance in which a class inherits from a
class which itself inherits from another class.
• Here a minimum of three classes is required.
• Hierarchy inheritance:- Here two or more classes inherits from one
class.
• Multiple inheritance:- A class inherits from two or more classes.
• This type of inheritance is not supported in Java through
class,it’s achieved Using interfaces.
• Hybrid Inheritance: In simple terms you can say that Hybrid
inheritance is a combination of Single and Multiple inheritance.
• A hybrid inheritance can be achieved in the java in a same way
as multiple inheritance can be!! Using interfaces.
17
Inheritance Types (2)
• A typical flow diagram would look like below.

18
Inheritance Types (3)
// Single Level Inheritance class TestInheritance{
Example public static void main(String args[])
class Animal { {
void eat(){ Dog jack=new Dog();
System.out.println("eating..."); jack.bark();
} jack.eat();
} }

class Dog extends Animal{ }


void bark(){ Output:
System.out.println("barking..."); barking…
}
eating...
}

19
Inheritance Types (4)
// Multi-Level Inheritance class class TestInheritance2{
Animal{
public static void main(String args[]){
void eat(){
System.out.println("eating..."); BabyDog d=new BabyDog();
} d.weep();
}
d.bark();
class Dog extends Animal{
void bark(){ d.eat();
System.out.println("barking..."); }
}
}
}
class BabyDog extends Dog{ Out put:
void weep(){ weeping…
System.out.println("weeping...");
}
barking…
} eating…

20
Inheritance Types (5)
// Hierarchical Inheritance class class TestInheritance3{
class Animal{
public static void main(String args[])
void eat(){
System.out.println("eating...");
{
} Cat c=new Cat();
} c.meow();
class Dog extends Animal{
void bark(){
c.eat();
System.out.println("barking..."); //c.bark();//C.T.Error
} }
}
class Cat extends Animal{ }
void meow(){ Output:
System.out.println("meowing..."); meowing…
}
eating…
}

21
Inheritance Types (6)
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were supported

Public Static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
} 22
Inheritance Types (7)
public class A {
public class C extends B {
public A() {
public C() {
System.out.println("I'm A");
System.out.println("I'm C");
}
}
}
}
public class B extends A {
What does this print out?
public B() {

System.out.println("I'm B"); C x = new C();

23
Inheritance Rules (1)
• Use the extends keyword to indicate that one class inherits
from another
• The subclass inherits all the nonprivate fields and methods of
the superclass
• Elements to be inherited from parent class are protected and
public members.
• private members of the superclass are not inherited by the
subclass and can only be indirectly accessed.
• Members that have default accessibility in the superclass are
also not inherited by subclasses in other packages.
• Use the super keyword in the subclass constructor to call the
superclass constructor

24
Inheritance Rules (2)
• An instance method can be overridden only if it is accessible.
• Thus a private method cannot be overridden, because it is not
accessible outside its own class.
• If a method defined in a subclass, is private in its superclass,
the two methods are completely unrelated.

25
SubClass Constructor (1)
• The first thing a subclass constructor must do is call the
superclass constructor using super keyword
• This ensures that the superclass part of the object is
constructed before the subclass part
• If you do not call the superclass constructor with the super
keyword, and the superclass has a constructor with no
arguments, then that superclass constructor will be called
implicitly.

26
Subclass Constructor (2)
//Implicit Super //then this Beef subclass: //is equivalent to:
Constructor Call public class Beef extends Food { public class Beef extends Food {
//If I have this Food private double weight; private double weight;
class:
public Beef(double w) { public Beef(double w) {
public class Food { super();
weight = w;
boolean raw; weight = w;
}
} boolean raw; }
public Food() { }
raw = true;
}
}

27
Subclass Constructor (3)
In sub-classes we can inherit members as is, replace them, hide them,
or supplement them with new members:
– The inherited fields can be used directly, just like any other fields.

– We can declare new fields in the subclass that are not in the superclass.

– The inherited methods can be used directly as they are.

– We can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it.

– We can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.

– We can declare new methods in the subclass that are not in the superclass.

– We can write a subclass constructor that invokes the constructor of the


superclass, either implicitly or by using the keyword super.
28
Important Points (1)
• Code reuse is the most important benefit of inheritance because subclasses
inherits the variables and methods of superclass.
• Private members of superclass are not directly accessible to subclass.
Superclass members with default access is accessible to subclass ONLY if
they are in same package.
• Superclass constructors are not inherited by subclass.
• If superclass doesn’t have default constructor, then subclass also needs to
have an explicit constructor defined. Else it will throw compile time
exception.
– In the subclass constructor, call to superclass constructor is mandatory
in this case and it should be the first statement in the subclass
constructor.
• Java doesn’t support multiple inheritance, a subclass can extends only one
class. 29
Important Points (2)
• We can create an instance of subclass and then assign it to superclass
variable, this is called upcasting.
• Below is a simple example of upcasting:
Cat c = new Cat(); //subclass instance
Animal a = c; // it's fine since Cat is also an Animal
• When an instance of Superclass is assigned to a Subclass variable, then it’s
called downcasting.
• We need to explicitly cast this to Subclass. For example;
Cat c = new Cat();
Animal a = c;
Cat c1 = (Cat) a; // works fine because "c" is actually of type Cat
30
Important Points (3)
• Note that Compiler won’t complain even if we are doing it
wrong, because of explicit casting.
• Below are some of the cases where it will throw
ClassCastException at runtime.
Dog d = new Dog();
Animal a = d;
Cat c1 = (Cat) a; //ClassCastException at runtime
Animal a1 = new Animal();
Cat c2 = (Cat) a1; //ClassCastException because a1 is actually
of type Animal at runtime
31
Important Points (4)
• We can call the superclass methods and access superclass
variables using super keyword.
• It comes handy when we have the same name variable/method
in the subclass but we want to access the superclass
variable/method.
• This is also used when Constructors are defined in the
superclass and subclass and we have to explicitly call the
superclass constructor.

32
Important Points (5)
• We can use instanceof instruction to check the inheritance
between objects, let’s see this with below example.
Cat c = new Cat();
Dog d = new Dog();
Animal a = c;
boolean flag = c instanceof Cat; //normal case, returns true
flag = c instanceof Animal; // returns true since c is-an Animal too
flag = a instanceof Cat; //returns true because a is of type Cat at
runtime
flag = a instanceof Dog; //returns false for obvious reasons.
33
Important Points (6)
• We can override the method of Superclass in the Subclass.
• However we should always annotate overridden method with
@Override annotation.
• The compiler will know that we are overriding a method and if
something changes in the superclass method, we will get a compile-time
error rather than getting unwanted results at the runtime.
• We can’t extend Final classes in java.
• If you are not going to use Superclass in the code i.e your Superclass is
just a base to keep reusable code then you can keep them as Abstract
class to avoid unnecessary instantiation by client classes.
• It will also restrict the instance creation of base class.

34
Quiz
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("Faculty's no-arg constructor is invoked");
}
}
//*********************************************************************
class Employee extends Person {
public Employee() {
this("Invoke Employee’s overloaded constructor");
System.out.println("Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
//************************************************************************
class Person {
public Person() {
System.out.println("Person's no-arg constructor is invoked");
}
}

35
Ouput
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
System.out.println("(4) Faculty's no-arg constructor is invoked");
}
}
//*********************************************************************
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
System.out.println("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
System.out.println(s);
}
}
//************************************************************************
class Person {
public Person() {
System.out.println("(1) Person's no-arg constructor is invoked");
}
}

36
Questions?

37

You might also like