0% found this document useful (0 votes)
4 views15 pages

Ch4 Inheritance

Chapter 4 discusses inheritance in Object Oriented Programming, explaining how a derived class (subclass) inherits properties and behaviors from a base class (superclass). It covers various types of inheritance such as single, multilevel, hierarchical, and notes that Java does not support multiple inheritance. The chapter also explains the use of 'super' and 'this' keywords in Java for referencing parent class members and current class instances, respectively.

Uploaded by

Ebiyo Faf
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)
4 views15 pages

Ch4 Inheritance

Chapter 4 discusses inheritance in Object Oriented Programming, explaining how a derived class (subclass) inherits properties and behaviors from a base class (superclass). It covers various types of inheritance such as single, multilevel, hierarchical, and notes that Java does not support multiple inheritance. The chapter also explains the use of 'super' and 'this' keywords in Java for referencing parent class members and current class instances, respectively.

Uploaded by

Ebiyo Faf
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/ 15

SUBJECT: OPPs (CoSc2051) 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
own attributes which makes it different from other subclasses. By using inheritance we need not rewrite the

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 2

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

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 3

Inheritance Example3
public class WollegaUniversity {
public AllResources(){
String Cars;
String SportPlace;
}
}

public class CompScience extendes WollegaUniversity {


public void CompResource() {
String Computer;
}
public static void main(String args[ ] ){
CompScience CS= new CompScience();
CS. AllResources();
CS. CompResource()
}
}

public class Biology extendes WollegaUniversity {


public void BiologyResource(){
String laboratory;
}
public static void main(String args[] ){
Biology Bio= new Biology();
Bio. AllResources();
Bio. BiologyResource()
}
}

Here WollegaUniversity is a parent/main/super/base class and both CompScience and


Biology are child/sub/derived classes .

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 4

Inheritance Example3
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.

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 5

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

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 6

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


class Employee {
private int eno;
private String ename;
public void setemp(int no,String name) {
eno = no;
ename = name;
}
public void putemp() {
System.out.println("Empno : " + eno);
System.out.println("Ename : " + ename);
}}

class Department extends Employee{


private int dno;
private String dname;
public void setdept(int no,String name) {
dno = no;
dname = name;
}
public void putdept() {
System.out.println("Deptno : " + dno);
System.out.println("Deptname : " + dname);
}
public static void main(String args[]){
department d = new department();
d.setemp(100,"aaaa");
d.setdept(20,"Sales");
d.putemp();
d.putdept();
}}

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 7

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

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 8

Multilevel inheritance example java program

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.

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 9

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

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 10

 We have noticed that multiple inheritances is not supported in java classes but it’s supported in interfaces.
 A single interface can extend multiple interfaces.

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 11

Why multiple inheritance is not supported in Java class


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

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (CoSc2051) Ch:4 INHERITANCE 12

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.

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (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.

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


SUBJECT: OPPs (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.

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE


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

Prepared by: Dr. Obsa G WOLLEGA UNIVERSITY, NEKEMTE

You might also like