Chapter-Three (Inheritance)

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 40

BITS College

Undergraduate Program
Course Code: SE132
Course Title: Object Oriented
Programming
Chapter 3: Inheritance
Contents

Introduction
Super-classes and Sub-classes
Protected members
Overriding methods
Using this and super
Use of the final keyword with inheritance
Constructors in sub-classes
Introduction
 Inheritance is one of the key features of OOP that allows us to create
a new class from an existing class.
– It is the ability to derive something specific from something generic.
 A class can inherit the features of another class and add its own
modification
– The existing class is called the parent class, or superclass, or base class
– The derived class is called the child class or subclass
Cont...
 As the name implies, the child inherits characteristics of the parent
– That is, the child class (subclass) inherits all the properties and methods of
the parent (super) class
 Proper inheritance creates an is-a relationship, meaning the child is a
more specific version of the parent

Vehicle

Car
Is-a Relationship
 In Java, inheritance is an is-a relationship. That is, we use inheritance
only if there exists an is-a relationship between two classes.
 For example,
– Car is a Vehicle
– Orange is a Fruit
– Surgeon is a Doctor
– Dog is an Animal
 Here, Car can inherit from Vehicle, Orange can inherit from Fruit,
and so on.
Why Inheritance?
 The most important use of inheritance in Java is code reusability.
– The code that is present in the parent class can be directly used by the child
class.
 Method overriding is also known as runtime polymorphism.
– Hence, we can achieve Polymorphism in Java with the help of inheritance.
Types of Inheritance
 There are four types of inheritance.
– Single inheritance
– Multiple inheritance
– Hierarchical inheritance
– Multilevel inheritance
Cont...
 Single Inheritance
– In single inheritance, a single subclass extends from a single superclass.
– For example,
Cont...
Multilevel Inheritance
– In multilevel inheritance, a subclass extends from a superclass and then the
same subclass acts as a superclass for another class.
– For example
Cont…
 Hierarchical Inheritance
– In hierarchical inheritance, multiple subclasses extend from a single
superclass.
– For example,
Cont…
 Multiple Inheritance
– In multiple inheritance, a single subclass extends from multiple super
classes.
– Note: Java doesn't support multiple inheritance
– For example,
Super and Sub Classes
 The aim of inheritance is to provide the reusability of code so that
– A class has to write only the unique features and
– Rest of the common properties and functionalities can be extended from the
another class.
 Sub class
– The class that extends the features of another class is known as child
class, sub class or derived class.
 Super class
– The class whose properties and functionalities are used(inherited) by
another class is known as parent class, super class or Base class.
extends keyword
 The extends keyword is used to perform inheritance in Java.
 Here class Car is child class and class Vehicle is parent class.
 The class Car is inheriting the properties and methods of Vehicle class.
class Car extends Vehicle {

}
Example

 Classes in Java support single inheritance; the Car class can't


extend multiple classes.
Also, note that in the absence of an extends keyword, a class implicitly
inherits class java.lang.Object.
Cont...
 A subclass class inherits the protected and public members from
the superclass class.
– In addition, the members with default and package access are inherited if
the two classes are in the same package.
 On the other hand, the private members of a class are not inherited.
 To access inherited properties or methods, we can simply use them
directly:
– Note that we don't need a reference to the superclass to access its members
Protected Members
 A class's public members are accessible wherever the program has a
reference to an object of that class or one of its subclasses.
A class's private members are accessible only from within the class
itself. A superclass's private members are not inherited by its
subclasses.
 Using protected access offers an intermediate level of access
between public and private.
Inheritance and Method Overriding
 When we declare the same method in child class which is already
present in the parent class this is called method overriding.
– In this case when we call the method from child class object, the child class
version of the method is called.
 However we can call the parent class method using super keyword.
Cont...
 Usage of Java Method Overriding
– Method overriding is used to provide the specific implementation of a
method which is already provided by its superclass.
– Method overriding is used for runtime polymorphism
 Rules for Java Method Overriding
– The method must have the same name as in the parent class
– The method must have the same parameter as in the parent class.
– There must be an IS-A relationship (inheritance).
Example
Cont...
 Method overriding properties
– Overriding and Access-Modifiers : The access modifier for an overriding
method can allow more, but not less, access than the overridden method.
– Final methods can not be overridden : If we don’t want a method to be
overridden, we declare it as final.
– Static methods can not be overridden: When you define a static method
with same signature as a static method in base class, it is known as method
hiding.
Cont...

– Invoking overridden method from sub-class : We can call parent class


method in overriding method using super keyword.
– Overriding and constructor : We can not override constructor as parent
and child class can never have constructor with same name(Constructor
name must always be same as Class name).
Using this and Super keyword
 Java provides two useful implicit reference variables ‘this’ and
‘super’.
– Both are used to resemble the reference variable pointing to the super class
and subclass
Cont...
 this Keyword
– It is an implicit reference variable that is used to refer current class objects
– It invokes the constructor of subclass
– In the case of overridden methods, this keyword is used to invoke the
method of subclass
– It solves the problem of variable hiding. Using this keyword, a compiler
always refers to instance variable of the current class.
– It can be used to return and pass as an argument in context of current
class object
Cont...
 super Keyword
– It is an implicit reference variable that is used to refer child class’s
immediate parent class objects.
– It invokes the constructor of superclass
– In the case of the overridden method, super keyword is used to invoke the
method of superclass.
– Using super keyword, compiler always refer to immediate parent class
instance variable.
– It can be used to return and pass as an argument in context of parent
class object.
Java Inheritance Hiding(Shadowing)
 Variable Hiding
– When both the child and the parent classes have a variable with the same
name, the child's variable hides the one from the parent.
Cont...
Cont…
 To test it, let's initialize two instances. One with parent class and
another with the child, then invoke the printInstanceVariable() methods
on each of them:
Cont…
 Method Hiding
– Method hiding may happen in any hierarchy structure in java.
– When a child class defines a static method with the same signature as a
static method in the parent class, then the child's method hides the one in the
parent class.
– The same behavior involving the instance methods is called method
overriding.
Cont…
Cont…
 Method Hiding vs Overriding
– Hiding doesn't work like overriding, because static methods are not
polymorphic.
– Overriding occurs only with instance methods.
– It supports late binding, so which method will be called is determined at runtime.
– On the other hand, method hiding works with static ones. Therefore it's
determined at compile time.
final keyword
 Java final keyword is a non-access specifier that is used to restrict a
class, variable, and method.
– Declaring constants (used with variable and argument declaration)
• final int MAX=100;
– Disallowing method overriding (used with method declaration)
• final void show (final int x)
– Disallowing inheritance (used with class declaration).
• final class Demo {}
Example
class Parent {
final void final_method() {
//definition of the Final Method
}
}
class Child extends Parent {
final void final_method(){
//generates a compile-time error
}
}
Constructor in subclass
 A class that extends another class does not inherit its constructors.
– However, the subclass must call a constructor in the superclass inside of
its the subclass constructors!
– If a subclass calls another constructor within itself, then the called
constructor must call the superclass constructor.
– To invoke a superclass's constructor, use the super keyword
Cont...

– Invocation of a superclass constructor must be the first line in the subclass


constructor.
– The syntax for calling a superclass constructor is
super();
the superclass no-argument constructor is called.
or:
super(parameter list);
the superclass constructor with a matching parameter list is called.
Example
public Box()
{
super();
height = 0;
}

public Box(double l, double w, double h)


{
super(l, w);
height = h;
}
Abstract class and method
 An abstract class is a class that is declared abstract - it may or may not include
abstract methods
 Abstract classes cannot be instantiated, but they can be subclassed.
 An abstract method is a method that is declared without an implementation
 If a class contains an abstract method, then the class must be declared as
abstract
 When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class. However, if it
does not, then the subclass must also be declared abstract.
Cont...
 Example
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}

class Circle extends GraphicObject {


void draw() {
...
}
void resize() {
...
}
}

class Rectangle extends GraphicObject {


void draw() {
...
}
void resize() {
...
}
}
Interface
 Is a fully abstract class
 It is a “contract” that specifies what a method should look like
public interface OperateCar {

// constant declarations, if any

// method signatures

// An enum with values RIGHT, LEFT


int turn(Direction direction, double radius, double startSpeed, double endSpeed);
int changeLanes(Direction direction, double startSpeed, double endSpeed);
int signalTurn(Direction direction, boolean signalOn);
int getRadarFront(double distanceToCar, double speedOfCar);
int getRadarRear(double distanceToCar, double speedOfCar);
......
// more method signatures
}
Cont...
 Which should you use, abstract classes or interfaces?
– Consider using abstract classes if any of these statements apply to your situation:
• You want to share code among several closely related classes.
• You expect that classes that extend your abstract class have many common methods or fields, or require access
modifiers other than public (such as protected and private)
• You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the
state of the object to which they belong.
– Consider using interfaces if any of these statements apply to your situation:
• You expect that unrelated classes would implement your interface.
• You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
• You want to take advantage of multiple inheritance of type.

You might also like