Chapter 4: Inheritance: Introduction
Chapter 4: Inheritance: Introduction
CHAPTER 4: INHERITANCE
Introduction
Inheritance is one of the key features of Object Oriented Programming. Inheritance provided mechanism
that allowed a class to inherit property of another class. Inheritance can be best understood in terms of
Parent and Child relationship, in other words, the derived class inherits the states and behaviours from the
base class. The derived class is also called subclass and the base class is also known as superclass. The
derived class can add its own additional variables and methods. These additional variable and methods
differentiates the derived class from the base class. When a Class extends another class it inherits all non-
private members including fields and methods. extends and implements keywords are used to describe
inheritance in Java.
class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}
Inheritance Example1
Let’s consider a superclass Vehicle. Different vehicles have different features and properties however there
few of them are common to all. Speed, colour, fuel used, size are few which are common to all. Hence we
can create a class ‘Vehicle’ with states and actions that are common to all vehicles. The subclass of this
superclass can be any type of vehicle. Example: Class Car has all the features of a vehicle. But it has its
own attributes which makes it different from other subclasses. By using inheritance we need not rewrite the
code that we’ve already used with the Vehicle. The subclass can also be extended. We can make a class
‘Sports Car’ which extends ‘Car’. It inherits the features of both ‘Vehicle’ and ‘Car’.
Here is the complete example:
The output is
Color of Car : Blue
Speed of Car : 200
Size of Car : 22
CC of Car : 1000
No of gears of Car : 5
Inheritance Example2
In this example we can observe two classes namely Calculation and My_Calculation. Using extends
keyword the My_Calculation inherits the methods addition() and Subtraction() of Calculation class.
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 Substraction(int x,int y){
z = x-y;
System.out.println("The difference between the given numbers:"+z);
}}
The Superclass reference variable can hold the subclass object, but using that variable we can access only
the members of the superclass, so to access the members of both classes it is recommended to always
create reference variable to the subclass.
If we consider the above program we can instantiate the class as given below as well. But using the
superclass reference variable (cal in this case ) we cannot call the method multiplication(), which belongs
to the subclass My_Calculation.
Calculation cal = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass.
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Not supported by JAVA)
1) Single Inheritance:
When a class extends another one class only then we call it a single inheritance. The flow diagram
shows that class B extends only one class which is A. Here A is a parent class of B and B would be a
child class of A.
Single Inheritance example program in Java
Class A{
public void methodA() {
System.out.println("Base class method");
}}
Class B extends A{
public void methodB() {
System.out.println("Child class method");
}
public static void main(String args[]){
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}}
2) Multilevel 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. As we can see in the flow diagram C is
subclass or child class of B and B is a child class of A.
Class Y extends X{
public void methodY() {
System.out.println("class Y method");
}}
Class Z extends Y{
public void methodZ() {
System.out.println("class Z method");
}
public static void main(String args[]) {
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}}
WOLLEGA UNIVERSITY, NEKEMTE
SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 7
class Students {
private int sno;
private String sname;
public void setstud(int no,String name) {
sno = no;
sname = name;
}
public void putstud() {
System.out.println("Student No : " + sno);
System.out.println("Student Name : " + sname);
}}
3) Hierarchical Inheritance:
In such kind of inheritance one class is inherited by many sub classes. As shown in the flow diagram class
B,C and D inherits the same class A. A is parent class (or base class) of B, C & D.
class A
class HierarchicalInheritance {
void DisplayA() {
System.out.println("This is a content of parent class");
}}
//B.java
class A extends HierarchicalInheritance {
void DisplayB() {
System.out.println("This is a content of child class 1");
} }
//c.java
class B extends HierarchicalInheritance {
void DisplayC() {
System.out.println("This is a content of child class 2");
}}
//MainClass.java
class HierarchicalInheritanceMain {
public static void main(String args[]) {
System.out.println("Calling for child class C");
B b = new B();
b.DisplayA();
b.DisplayC();
System.out.println("Calling for child class B");
A a = new A();
a.DisplayA();
a.DisplayB();
}}
4) Multiple Inheritance:
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base class.
The inheritance we learnt earlier had the concept of one base class or parent. The problem with “multiple
inheritance” is that the derived class will have to manage the dependency on two base classes.
Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance. Multiple
Inheritance is supported in C++.
In the above example Vehicle and Bike both class have a common property speed. Instance variable of
current class is referred by instance by default, but we have to refer parent class instance variable that is
why we use super keyword to distinguish between parent class instance variable and current class instance
variable.
//example of this keyword
class Student11{
int id;
String name;
Student11(int id, String name){
this.id = id;
this.name = name;
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Guluma");
Student11 s2 = new Student11(222,"Gedeta");
s1.display();
s2.display();
} }
In the above example, parameter (formal arguments) and instance variables are same that is why we are
using this keyword to distinguish between local variable and instance variable.
class Student13{
int id;
String name;
Student13(){ System.out.println("default constructor is invoked"); }
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name; }
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}}
In this example, we have defined the run method in the subclass as defined in the parent class but it has
some specific implementation. The name and parameter of the method is same and there is IS-A
relationship between the classes, so there is method overriding.
class Vehicle{
void run(){
System.out.println("Vehicle is running");\
}
}
class Bike2 extends Vehicle{
void run(){
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();
obj.run();
} }
Another example of super keyword in Method Overriding: In the given program we have two
classes namely Sub_class and Super_class, both have a method named display() with different
implementations, and a variable named num with different values. We are invoking display() method of
both classes and printing the value of the variable num of both classes, here we can observe that we have
used super key word to differentiate the members of super class from sub class.
class Super_class{
int num = 20;
//display method of superclass
public void display(){
System.out.println("This is the display method of superclass");
}}
Java - Interfaces
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. Java Interface is not a class but it is defined in
away similar to the class definition. An Interface describes the functions and behaviors of a specific object
type but doesn't implement them. There can be only abstract methods in the java interface not method body
i.e. it is a collection of abstract methods. It is used to achieve fully abstraction and multiple inheritance in
Java.
A class implements an interface, thereby inheriting the abstract methods of the interface. Along with
abstract methods an interface may also contain constants, default methods, static methods, and nested
types. Method bodies exist only for default methods and static methods.
A class describes the attributes and behaviours of an object. And an interface contains behaviours
that a class implements. Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
An interface is similar to a class in the following ways:
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface matching the
name of the file.
The byte code of an interface appears in a .class file.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
However, an interface is different from a class in several ways, including:
We cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
An interface cannot contain instance fields. The only fields that can appear in an interface must be
declared both static and final.
An interface is not extended by a class; it is implemented by a class.
An interface can extend multiple interfaces.
Declaring Interfaces:
The interface keyword is used to declare an interface.
Example:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements
Implementing Interfaces:
When a class implements an interface, we can think of the class as signing a contract, agreeing to perform
the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the
class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in the
class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{
public void eat(){ System.out.println("Mammal eats"); }
Example 2:
interface printable{ void print(); }
class A6 implements printable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
} }
When overriding methods defined in interfaces there are several rules to be followed:
Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be maintained
when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.
When implementation interfaces there are several rules:
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend another
class.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class. The
extends keyword is used to extend an interface, and the child interface inherits the methods of the parent
interface. The following Sports interface is extended by Hockey and Football interfaces.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Rugby.java
public interface Rugby extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the
three methods from Football and the two methods from Sports.
Example:
interface Printable{ void print(); }
interface Showable{ void show(); }
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
} }