Chapter 5 Inheritance
Chapter 5 Inheritance
Inheritance
• Method Overriding
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
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:
• 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
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.
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");
}
}
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; }
}
• 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.
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.
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:
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);
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.
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