0% found this document useful (0 votes)
43 views17 pages

Chapter 4: Inheritance: Introduction

The document discusses inheritance in object-oriented programming. It defines inheritance as a mechanism where a class can inherit properties from another class. This allows for code reusability. There are four main types of inheritance discussed: single inheritance where a class extends one parent class; multilevel inheritance where a class inherits from another derived class, making it the parent class; hierarchical inheritance where a class has multiple child classes; and multiple inheritance which is not supported in Java. Examples are provided to demonstrate single and multilevel inheritance in code. Benefits of inheritance include reduced development time, memory usage, and execution time through code reuse and redundancy reduction.

Uploaded by

Ebisa Damene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views17 pages

Chapter 4: Inheritance: Introduction

The document discusses inheritance in object-oriented programming. It defines inheritance as a mechanism where a class can inherit properties from another class. This allows for code reusability. There are four main types of inheritance discussed: single inheritance where a class extends one parent class; multilevel inheritance where a class inherits from another derived class, making it the parent class; hierarchical inheritance where a class has multiple child classes; and multiple inheritance which is not supported in Java. Examples are provided to demonstrate single and multilevel inheritance in code. Benefits of inheritance include reduced development time, memory usage, and execution time through code reuse and redundancy reduction.

Uploaded by

Ebisa Damene
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 1

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.

Let us see how extend keyword is used to achieve Inheritance.


Now based on above example, in OOPs term we can say that,

class Vehicle.
{
......
}
class Car extends Vehicle
{
....... //extends the property of vehicle class.
}

 Vehicle is superclass (Base class) of Car.


 Car is subclass (derived class) of Vehicle.
 Car IS-A Vehicle.

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

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 2

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:

// A class to display the attributes of the vehicle


class Vehicle {
String color;
int speed;
int size;
void attributes() {
System.out.println("Color : " + color);
System.out.println("Speed : " + speed);
System.out.println("Size : " + size);
}
}

// A subclass which extends for vehicle


class Car extends Vehicle {
int CC;
int gears;
void attributes_car() {
// The subclass refers to the members of the superclass
System.out.println("Color of Car : " + color);
System.out.println("Speed of Car : " + speed);
System.out.println("Size of Car : " + size);
System.out.println("CC of Car : " + CC);
System.out.println("No of gears of Car : " + gears);
}
}

public class Test {


public static void main(String args[]) {
Car b1 = new Car();
b1.color = "Blue";
b1.speed = 200 ;
b1.size = 22;
b1.CC = 1000;
b1.gears = 5;
b1.attributes_car();
}
}

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

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 3

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);
}}

public class My_Calculation extends Calculation{


public void multiplication(int x, int y){
z = x*y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]){
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b);
}}

After executing the program it will produce the following result.


The sum of the given numbers:30
The difference between the given
numbers:10
The product of the given numbers:200
In the given program when an object to
My_Calculation class is created, a copy of
the contents of the super class is made with
in it. That is why, using the object of the
subclass we can access the members of a super class.

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 4

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.

 Purpose of Inheritance (What are the benefits of using


inheritance?)
If we develop any application using concept of Inheritance than that application have following
advantages,
 Application development time is less.
 Application take less memory.
 Application execution time is less.
 Application performance is enhance (improved).
 Redundancy (repetition) of the code is reduced or minimized so that we get consistence results and
less storage cost.

 Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Not supported by JAVA)

1) Single Inheritance:

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 5

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
}}

Single inheritance example program

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 6

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.

Multilevel inheritance example java program

Multilevel Inheritance example program in Java


Class X {
public void methodX() {
System.out.println("Class X method");
}}

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);
}}

class Marks extends Students {


        protected int mark1,mark2;
        public void setmarks(int m1,int m2) {
                mark1 = m1;
                mark2 = m2;
        }
        public void putmarks() {
                System.out.println("Mark1 : " + mark1);
                System.out.println("Mark2 : " + mark2);
}}

class Finaltot extends Marks


{
        private int total;
        public void calc() {
                total = mark1 + mark2;
        }
        public void puttotal() {
                System.out.println("Total : " + total);
        }
        public static void main(String args[]) {
                finaltot f = new finaltot();
                f.setstud(100,"Nithya");
                f.setmarks(78,89);
                f.calc();
                f.putstud();
                f.putmarks();
                f.puttotal();
}}

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.

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 8

class A

class B class C class D

Hierarchical Inheritance Example Program

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++.

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 9

Why multiple inheritance is not supported in Java


 To remove ambiguity.
 To provide more maintainable and clear design.

 The super Keyword


It is used inside a sub-class method definition to use data variable or to call a method defined in the
immediate parent class object. Whenever we create the instance of subclass, an instance of parent class is
created implicitly i.e. referred by super reference variable. Private methods of the super-class cannot be
called. Only public and protected methods can be called by the super keyword.

Usage of java super Keyword


1. It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
2. It is used to refer immediate parent class instance variable.
3. It is used to invoke immediate parent class constructor.
4. It is used to invoke immediate parent class method.
class Vehicle{  
  int speed=50;  }  
  
class Bike4 extends Vehicle{  
  int speed=100;  
void display(){  
   System.out.println(super.speed);//will print speed of Vehicle now  }  
  public static void main(String args[]){  
   Bike4 b=new Bike4();  
   b.display();   Output: 50
} }  

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 10

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.

 The this Keyword


In java, this is a reference variable that refers to the current object.

Usage of java this keyword


Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

//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.

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 11

Another example of this keyword (used to invoked current class constructor)

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();
}}

 Java Method Overriding


Declaring a method in subclass which is already present in parent class is known as method overriding. In
other words, If subclass provides the specific implementation of the method that has been provided by one
of its parent class, it is known as method overriding.

Usage of Java Method Overriding


 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

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example of method overriding

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.

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 12

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();  
}  }

Rules for method overriding:


 In java, a method can only be written in Subclass, not in same class.
 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the super class.
 The access level cannot be more restrictive than the overridden method’s access level. For
example: if the super class method is declared public then the overridding method in the sub class
cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited then it cannot be overridden.
 Constructors cannot be overridden.

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.

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 13

class Super_class{
int num = 20;
//display method of superclass
public void display(){
System.out.println("This is the display method of superclass");
}}

public class Sub_class extends Super_class {


int num = 10;
//display method of sub class
public void display(){
System.out.println("This is the display method of subclass");
}

public void my_method(){


//Instantiating subclass
Sub_class sub = new Sub_class();
//Invoking the display() method of sub class
sub.display();
//Invoking the display() method of superclass
super.display();
//printing the value of variable num of subclass
System.out.println("value of the variable named num in sub class:"+ sub.num);
//printing the value of variable num of superclass
System.out.println("value of the variable named num in super class:"+ super.num);
}

public static void main(String args[]){


Sub_class obj = new Sub_class();
obj.my_method();
}}

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 14

 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.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.
1. It is used to achieve fully abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 15

Declaring Interfaces:
The interface keyword is used to declare an interface.
Example:
/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements

public interface NameOfInterface


{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:


 An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an
interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.
Example:
/* File name : Animal.java */
interface Animal {

public void eat();


public void travel();
}

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"); }

public void travel(){ System.out.println("Mammal travels"); }

public int noOfLegs(){ return 0; }

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 16

This would produce the following result:


ammal eats
ammal travels

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);
}

WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (ENEg3142 / CoSc2082) Ch:4 INHERITANCE 17

//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.

Extending Multiple Interfaces:


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface. The extends keyword is used
once, and the parent interfaces are declared in a comma-separated list. For example, if the Hockey interface
extended both Sports and Event, it would be declared as:
public interface Hockey extends Sports, Event

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();  
} }

WOLLEGA UNIVERSITY, NEKEMTE

You might also like