0% found this document useful (0 votes)
2 views

Chapter 5 Inheritance

The document provides an overview of inheritance in Java, explaining its fundamental concepts, types, and syntax. It covers the use of keywords like 'super', 'abstract', and 'final', as well as method overriding and dynamic dispatch. Additionally, it discusses the advantages of inheritance, such as code reusability and reduced redundancy, while outlining various inheritance types including single, multilevel, hierarchical, and hybrid inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Chapter 5 Inheritance

The document provides an overview of inheritance in Java, explaining its fundamental concepts, types, and syntax. It covers the use of keywords like 'super', 'abstract', and 'final', as well as method overriding and dynamic dispatch. Additionally, it discusses the advantages of inheritance, such as code reusability and reduced redundancy, while outlining various inheritance types including single, multilevel, hierarchical, and hybrid inheritance.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Java Programming Language

Inheritance

Dr. K. Praveen Kumar


Sr. Assistant Professor, CSE Department
Overview
• Inheritance basics

• Using “Super” keyword

• Multilevel Hierarchy ( Types of Inheritance )

• Method Overriding

• Dynamic dispatch method

• Using “abstract” keyword

• Using “final” keyword


Inheritance : Basics
• What is Inheritance?
• The most fundamental element of Java is the class. A class represents
an entity and also, defines and implements its functionality. In Java,
classes can be derived from other classes, in order to create more
complex relationships.
• Inheritance is one of the key features of Object Oriented
Programming. Inheritance provides mechanism that allows a class to
inherit properties and methods of another class.
• Inheritance in java is used to add additional functionalities to the
existing class. Inheritance is used to extend the present class by
adding some more properties to it.
• Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
Contd.
• The idea behind inheritance in java 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 parent class, and you can add
new methods and fields also.
• In the inheritance the class which gives data members and methods is
known as base or super or parent class.
• The class which is taking the data members and methods is known as
sub or derived or child class.
• The data members and methods of a class are known as features.
• The concept of inheritance is also known as re-usability or extendable
classes or sub classing or derivation.
• Inheritance defines is-a relationship between a Super class and its Sub
class.
Contd.
• It is always good/“productive” if we are able to reuse something that is
already exists rather than creating the same all over again.
• This is achieve by creating new classes, reusing the properties of existing
classes.

Parent
Inherited
capability

Child
Syntax of Inheritance
( Implementation )

• The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality.
Why use Inheritance?
• Reusability--building new components by utilizing existing components- is yet
another important aspect of OO paradigm.
• It's main uses are to be able to reuse code for different classes by putting it in a
common super class.
• Application development time is less.
• Application take less memory.
• Application execution time is less.
• Application performance is enhanced (improved).
• Redundancy (repetition) of the code is reduced or minimized so that we get
consistence results and less storage cost.
Types of Inheritance?
• Based on number of ways inheriting the feature
of base class into derived class we have five
types of inheritance; they are:
• Single inheritance (only one super class)
• Multiple inheritance (several super classes)
• Hierarchical inheritance (one super class, many sub
classes)
• Multi-Level inheritance (derived from a derived
class)
• Hybrid inheritance (more than two types)
• Multi-path inheritance (inheritance of some
properties from two sources).
A A B A

B C B C D

(b) Multiple Inheritance


(a) Single Inheritance (c) Hierarchical Inheritance

A A
A

B c B c
B

C D D
(a) Multi-Level Inheritance (e) Hybrid Inheritance (f) Multipath
Inheritance
Defining a Sub class
• A subclass/child class is defined as follows:

class SubClassName extends SuperClassName


{
fields declaration;
methods declaration;
}

• The keyword “extends” signifies that the properties of super class are
extended to the subclass. That means, subclass contains its own
members as well of those of the super class.
Contd.
• A class can be defined as a "subclass" of another class.
• The subclass inherits all non-private data members of its superclass
• The subclass inherits all methods of its superclass
• The subclass inherits all associations of its superclass

• The subclass can:


• Add new functionality
• Use inherited functionality Person
• Override inherited functionality Superclass: - name: String
- dob: Date

Subclass: Employee
- employeeID: int
- salary: int
- startDate: Date
Contd…. What really happens?
• When an object is created using new, the system must allocate
enough memory to hold all its instance variables.
• This includes any inherited instance variables
• In this example, we can say that an Employee "is a kind of"
Person.
• An Employee object inherits all of the attributes, methods and associations
of Person

Person
- name: String
- dob: Date Person
name = "John Smith" Employee
dob = Jan 13, 1954 name = "Sally Halls"
is a kind of dob = Mar 15, 1968
Employee employeeID = 37518
- employeeID: int salary = 65000
- salary: int startDate = Dec 15,
- startDate: Date 2000
Example
• Let's understand these concept by an example
Example
Example
Single-Level Inheritance
• Single inheritance enables a derived class to inherit properties and behavior
from a single parent class. It allows a derived class to inherit the properties
and behavior of a base class.
Multi-Level Inheritance
• Multilevel inheritance refers to a mechanism in OO technology where one
can inherit from a derived class, thereby making this derived class the base
class for the new class.
Hierarchical-Inheritance
• In such kind of inheritance one class is inherited by many sub classes.
Contd.
• Each Java class has one (and only one)
superclass.
• inheritance creates a class hierarchy
• Classes higher in the hierarchy are more
general and more abstract.
• Classes lower in the hierarchy are more
specific and concrete.
• There is no limit to the number of subclasses
a class can have. There is no limit to the
depth of the class tree.
Hybrid Inheritance
• Combination of any inheritance type. In the combination if one of the
combination is multiple inheritance then the inherited combination is not
supported by java through the classes concept but it can be supported
through the concept of interface.
Multiple Inheritance
• “Multiple Inheritance” refers to the concept of one class extending (Or
inherits) more than one base class.
Constructors and Initialization
• Classes use constructors to initialize instance variables.
• When a subclass object is created, its constructor is called.
• It is the responsibility of the subclass constructor to invoke the appropriate
Superclass constructors so that the instance variables defined in the Superclass
are properly initialized.

• Superclass constructors can be called using the "super" keyword in a


manner similar to "this"

• It must be the first line of code in the constructor

• If a call to super is not made, the system will automatically attempt to


invoke the no-argument constructor of the Superclass
The “super” keyword
• The super keyword is similar to this keyword following are the
scenarios where the super keyword is used.
• It is used to differentiate the members of superclass from
the members of subclass, if they have same names.
• It is used to invoke the superclass constructor from subclass.
• 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();

27
// super keyword in java example // super keyword in java example

// superclass Person
// Base class vehicle class Person {
class Vehicle { void message()
int maxSpeed = 120; {
System.out.println("This is person class\
} n");
}
// sub class Car extending vehicle }
class Car extends Vehicle { // Subclass Student
class Student extends Person {
int maxSpeed = 180; void message()
{
void display() System.out.println("This is student
class");
{ }
// print maxSpeed of base class // Note that display() is
(vehicle) // only in Student class
System.out.println("Maximum Speed: void display()
{
" // will invoke or call current
+ // class message() method
super.maxSpeed); message();
}
// will invoke or call parent
} // class message() method
super.message();
// Driver Program }
}
class Test { // Driver Program
public static void main(String[] args) class Test {
{ public static void main(String args[])
Car small = new Car(); {
Student s = new Student();
small.display();
} // calling display() of Student
} s.display();
}
}
// Java Code to show use of
// super keyword with constructor

// superclass Person
class Person {
Person()
{
System.out.println("Person class
Constructor");
}
}

// subclass Student extending the Person


class
class Student extends Person {
Student()
{
// invoke or call parent class
constructor
super();

System.out.println("Student class
Constructor");
}
}

// Driver Program
class Test {
public static void main(String[] args)
{
Student s = new Student();
}
}
Shadowed Variables ( Re-visited )
• Subclasses defining variables with the same name as those in the
superclass, shadow them
public class Circle {
public float r ;
}
public class GraphicCircle extends Circle {
public float r ; // New variable, resolution in dots per inch
GraphicCircle( ) { super.r=90; r=20; }
}

public class CircleTest {


public static void main(String[] args){
GraphicCircle gc = new GraphicCircle();
Circle c = new Circle();
System.out.println(“ GraphicCircleRadius= “ + gc.r); // 20
System.out.println (“ Circle Radius = “ + c.r); // 90
}
}
Overriding Methods
• What is Method Overriding?
• Overloading occurs when two or more methods in one class have the same
method name but different parameters.
• Overriding here means having two methods with the same method name
and parameters in two different classes.
• Whenever same method name is existing in both base class and derived
class with same types of parameters or same order of parameters is known
as method Overriding.
• In the previous topic, we talked about Superclasses and Subclasses. If a
class inherits a method from its Superclass, then there is a chance to
override the method provided that it is not marked final.
• Advantages of Method Overriding?
• ability to define a behavior that's specific to the subclass type, which means a
subclass can implement a parent class method based on its requirement.
// Java program to demonstrate // Driver class
// method overriding in java class Main {
public static void main(String[] args)
// Base Class {
class Parent { // If a Parent type reference refers
void show() // to a Parent object, then Parent's
{ System.out.println("Parent's // show is called
show()"); } Parent obj1 = new Parent();
} obj1.show();

// Inherited class // If a Parent type reference refers


class Child extends Parent { // to a Child object Child's show()
// This method overrides show() of // is called. This is called RUN TIME
Parent // POLYMORPHISM.
@Override void show() Parent obj2 = new Child();
{ obj2.show();
Child obj3 = new Child();
System.out.println("Child's show()"); obj3.show();
} }
} }
1.//
Java Program to demonstrate the real scenario of Java Method Overrid
ing
2.//where three classes are overriding the method of a parent class.
3.//Creating a parent class.
4.class Bank{
5.int getRateOfInterest(){return 0;}
6.}
7.//Creating child classes.
8.class SBI extends Bank{
9.int getRateOfInterest(){return 8;}
10.}
11.
12.class ICICI extends Bank{
13.int getRateOfInterest(){return 7;}
14.}
15.class AXIS extends Bank{
16.int getRateOfInterest(){return 9;}
17.}
18.//Test class to create objects and call the methods
19.class Test2{
20.public static void main(String args[]){
21.SBI s=new SBI();
22.ICICI i=new ICICI();
23.AXIS a=new AXIS();
24.System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
25.System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

26.System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest())


;
Rules of Method Overriding
• Advantages
• Method Overriding is used to provide specific implementation
of a method that is already provided by its super class.
• Method Overriding is used for Runtime Polymorphism.
• Runtime polymorphism or Dynamic Method Dispatch is a
process in which a call to an overridden method is resolved at
runtime rather than compile-time.
• In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable.
• What methods can be overridden?
Rule #1:Only inherited methods can be overridden.
• Because overriding happens when a subclass re-implements a
method inherited from a superclass, so only inherited
methods can be overridden, that’s straightforward. Private
methods cannot be overridden.
• class Vehicle {
• public void drive() {
• System.out.println("Driving a vehicle");
• }
• }
• class Car extends Vehicle {
• @Override
• public void drive() {
• System.out.println("Driving a car"); Upcasting is a type of object typecasting
• } in which a child object is typecasted to a
• } parent class object.
• public class Main { Upcasting allows us to call overridden
• public static void main(String[] args) { methods of child classes on parent class
• Car ca = new Car(); objects.
• ca.drive(); // Output: Driving a car
• Vehicle ve = new Car();
• ve.drive(); // Output: Driving a car
• Vehicle ve1 = new Vehicle();
• ve1.drive(); // Output: Driving a vehicle
• }
• }
Rules of Method Overriding
• Rule #2: The argument list should be exactly the same as that of the overridden
method.

• Rule #3: The return type should be the same or a subtype of the return type
declared in the original overridden method in the superclass.

• Rule #4: The access level cannot be more restrictive than the overridden
method's access level. For example: If the superclass method is declared public
then the overriding method in the sub class cannot be either private or
protected.

• Rule #5: Instance methods can be overridden only if they are inherited by the
subclass.

• Rule #6: A method declared final cannot be overridden.


Final Members: A way for Preventing
Overriding of Members in Subclasses
• All methods and variables can be overridden by default in
subclasses.
• This can be prevented by declaring them as final using
the keyword “final” as a modifier. For example:
• final int marks = 100;
• final void display();
• This ensures that functionality defined in this method
cannot be altered any. Similarly, the value of a final
variable cannot be altered.

37
Final Classes: A way for Preventing
Classes being extended
• We can prevent an inheritance of classes by other classes by
declaring them as final classes.
• This is achieved in Java by using the keyword final as follows:
final class Marks
{ // members
}
final class Student extends Person
{ // members
}
• Any attempt to inherit these classes will cause an error.

38
Abstraction in Java
• Abstraction is a process of hiding the implementation details and
showing only functionality to the user.
• Another way, it shows only important things to the user and hides
the internal details for example sending sms, you just type the text
and send the message. You don't know the internal processing
about the message delivery.
• Abstraction lets you focus on what the object does instead of how
it does it.
• Ways to achieve Abstraction
• There are two ways to achieve abstraction in java
• Abstract class (0 to 100%)
• Interface (100%)

39
Abstract Classes
• When we define a class to be “final”, it cannot be extended. In
certain situation, we want to use properties of classes to be
always extended and used. Such classes are called Abstract
Classes.

• A class that is declared as abstract is known as abstract class. It


needs to be extended and its method implemented. It cannot be
instantiated.

• It can be used only as a super-class for those classes that extend


the abstract class.

• Java Abstract classes are used to declare common characteristics


of subclasses. An Abstract class cannot be instantiated – objects
cannot be created.
Abstract classes
• You must declare the class with the keyword abstract:
abstract class MyClass {...}

• You cannot instantiate (create a new instance of) an


abstract class.
• If a class has one or more abstract methods, it must be
declared as abstract
• You can declare a class to be abstract even if it does
not contain any abstract methods.
• This prevents the class from being instantiated.

41
Why have abstract classes?
• Suppose you wanted to create a class Shape, with
subclasses Oval, Rectangle, Triangle, Hexagon,
etc.
• You don’t want to allow creation of a “Shape”
• Only particular shapes make sense, not generic ones
• If Shape is abstract, you can’t create a new
Shape
• You can create a new Oval, a new Rectangle,
etc.
• Abstract classes are good for defining a general
category containing specific, “concrete” classes
42
An example abstract class
• Abstract classes provides a common root for a group of classes,
nicely tied together in a package:

• public abstract class Animal {


abstract int eat();
abstract void breathe();
}
• This class cannot be instantiated
• Any non-abstract subclass of Animal must provide the eat()
and breathe() methods

43
Why have abstract methods?
• The abstract Method is used for creating blueprints for classes
or interfaces.
• Here methods are defined but these methods don't provide
the implementation. Abstract Methods can only be
implemented using subclasses.
• Thus, a subclass must override them to provide a method
definition.
• Ex: abstract type method-name(parameter-list);
public abstract int example(int a1, int a2);

• As you can see, no method body is present

44
Why have abstract methods?
• Let's take a real world scenario. You have declared a class
named Vehicle which contains a method drive().
• drive() defines the mechanism that how a particular
vehicle can be driven.
• Since there may be different driving mechanism for
different vehicles, we will not write the method definition
for drive(). ie, we would declare that method as abstract
in Vehicle class.
• Now, let's assume that we have two classes Bike and Car
and these both are extending Vehicle.
• So, we can define our drive() method in Bike and Car
classes as per our requirements.
Example
• abstract class Animal {
• abstract void makeSound();
• }
• class Dog extends Animal {
• // provide implementation of abstract method
• public void makeSound() {
• System.out.println("Bark bark");
• }
• }
• class Main {
• public static void main(String[] args) {
• // create an object of Dog class
• Dog d1 = new Dog();
• d1.makeSound();
• }
• }
46
Abstract Class Syntax
abstract class ClassName
{
...

abstract Type MethodName1();


Type Method2()
{
// method body
}
}

47
Abstract Classes Rules
• A class with one or more abstract methods is
automatically abstract and it cannot be instantiated.

• A class declared abstract, even with no abstract


methods can not be instantiated.

• A subclass of an abstract class can be instantiated if it


overrides all abstract methods by implementing them.

• A subclass that does not implement all of the superclass


abstract methods is itself abstract; and it cannot be
instantiated.

48
Summary
• If you do not want (properties of) your class to be
extended or inherited by other classes, define it as a
final class.
• Java supports this is through the keyword “final”.
• This is applied to classes.
• You can also apply the final to only methods if you do
not want anyone to override them.
• If you want your class (properties/methods) to be
extended by all those who want to use, then define it as
an abstract class or define one or more of its methods
as abstract methods.
• Java supports this is through the keyword “abstract”.
• Subclasses should implement abstract methods; otherwise,
they cannot be instantiated.
49
FAQ’s
• Can abstract class have constructors in Java? Yes
• Can abstract class be final in Java? No
• Can abstract class have static methods in Java? Yes
• Can you create an instance of abstract class? No
• Is it necessary for abstract class to have abstract method? No
• Can abstract class contains main method in Java? Yes
• Abstract class must have only abstract methods. True or False? False
• Can we instantiate a class which does not have even a single abstract
methods but declared as abstract? No
• Can we declare abstract methods as private? No
• Abstract classes can be nested. True or False? True
• Can we declare local inner classes as abstract? Yes

50

You might also like