100% found this document useful (6 votes)
16K views

Inheritance 2

Inheritance in Java allows one class to acquire properties and behaviors of another class. This allows for code reusability so that a class only needs to define unique features and can inherit common properties and methods from a parent class. A child class inherits from a parent class, also called a super class or base class. There are different types of inheritance like single, multilevel, hierarchical, and hybrid. Method overriding and the super keyword are also used in inheritance.

Uploaded by

Saffa Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
16K views

Inheritance 2

Inheritance in Java allows one class to acquire properties and behaviors of another class. This allows for code reusability so that a class only needs to define unique features and can inherit common properties and methods from a parent class. A child class inherits from a parent class, also called a super class or base class. There are different types of inheritance like single, multilevel, hierarchical, and hybrid. Method overriding and the super keyword are also used in inheritance.

Uploaded by

Saffa Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

nheritance in Java Programming with examples

BY CHAITANYA SINGH | FILED UNDER: OOPS CONCEPT

The process by which one class acquires the properties(data members) and functionalities(methods) of
another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common properties and functionalities can be
extended from the another class.
Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent
class, super class or Base class.

Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods.
Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class need not
be rewritten in the child class.

This means that the data members(instance variables) and methods of the parent class can be used in
the child class as.

If you are finding it difficult to understand what is class and object then refer the guide that I have
shared on object oriented programming: OOPs Concepts

Lets back to the topic:

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent class. The
class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC

Inheritance Example

In this example, we have a base class Teacher and a sub class PhysicsTeacher. Since


class PhysicsTeacher extends the designation and college properties and work() method from base class,
we need not to declare these properties and method in sub class.
Here we have collegeName, designation and work() method which are common to all the teachers so we
have declared them in the base class, this way the child classes
like MathTeacher, MusicTeacher and PhysicsTeacher do not need to write this code and can be used
directly from base class.

class Teacher {

String designation = "Teacher";

String collegeName = "Beginnersbook";

void does(){

System.out.println("Teaching");

public class PhysicsTeacher extends Teacher{

String mainSubject = "Physics";

public static void main(String args[]){

PhysicsTeacher obj = new PhysicsTeacher();

System.out.println(obj.collegeName);

System.out.println(obj.designation);

System.out.println(obj.mainSubject);

obj.does();

Output:

Beginnersbook

Teacher

Physics

Teaching
Based on the above example we can say that PhysicsTeacher IS-A Teacher. This means that a child class
has IS-A relationship with the parent class. This is inheritance is known as IS-A relationship between
child and parent class

Note:
The derived class inherits all the members and methods that are declared as public or protected. If the
members or methods of super class are declared as private then the derived class cannot use them
directly. The private members can be accessed only in its own class. Such private members can only be
accessed using public or protected getter and setter methods of super class as shown in the example
below.

class Teacher {

private String designation = "Teacher";

private String collegeName = "Beginnersbook";

public String getDesignation() {

return designation;

protected void setDesignation(String designation) {

this.designation = designation;

protected String getCollegeName() {

return collegeName;

protected void setCollegeName(String collegeName) {

this.collegeName = collegeName;

void does(){

System.out.println("Teaching");

}
public class JavaExample extends Teacher{

String mainSubject = "Physics";

public static void main(String args[]){

JavaExample obj = new JavaExample();

/* Note: we are not accessing the data members

* directly we are using public getter method

* to access the private members of parent class

*/

System.out.println(obj.getCollegeName());

System.out.println(obj.getDesignation());

System.out.println(obj.mainSubject);

obj.does();

The output is:

Beginnersbook

Teacher

Physics

Teaching

The important point to note in the above example is that the child class is able to access the private
members of parent class through protected methods of parent class. When we make a instance
variable(data member) or method protected, this means that they are accessible only in the class itself
and in child class. These public, protected, private etc. are all access specifiers and we will discuss them
in the coming tutorials.

Types of inheritance
To learn types of inheritance in detail, refer: Types of Inheritance in Java.
Single Inheritance: refers to a child and parent class relationship where a class extends the another class.

Multilevel inheritance: refers to a child and parent class relationship where a class extends the child
class. For example class C extends class B and class B extends class A.
Hierarchical inheritance: refers to a child and parent class relationship where more than one classes
extends the same class. For example, classes B, C & D extends the same class A.

Multiple Inheritance: refers to the concept of one class extending more than one classes, which means a
child class has two parent classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritance, read more about it here.
Hybrid inheritance: Combination of more than one types of inheritance in a single program. For example
class A & B extends class C and another class D extends class A then this is a hybrid inheritance example
because it is a combination of single and hierarchical inheritance.

Constructors and Inheritance

constructor of sub class is invoked when we create the object of subclass, it by default invokes the
default constructor of super class. Hence, in inheritance the objects are constructed top-down. The
superclass constructor can be called explicitly using the super keyword, but it should be first statement
in a constructor. The super keyword refers to the superclass, immediately above of the calling class in
the hierarchy. The use of multiple super keywords to access an ancestor class other than the direct
parent is not permitted.

class ParentClass{

//Parent class constructor

ParentClass(){

System.out.println("Constructor of Parent");

class JavaExample extends ParentClass{

JavaExample(){

/* It by default invokes the constructor of parent class

* You can use super() to call the constructor of parent.

* It should be the first statement in the child class

* constructor, you can also call the parameterized constructor

* of parent class by using super like this: super(10), now

* this will invoke the parameterized constructor of int arg

*/

System.out.println("Constructor of Child");

public static void main(String args[]){


//Creating the object of child class

new JavaExample();

Output:

Constructor of Parent

Constructor of Child

Inheritance and Method Overriding

When we declare the same method in child class which is already present in the parent class the this is
called method overriding. In this case when we call the method from child class object, the child class
version of the method is called. However we can call the parent class method using super keyword as I
have shown in the example below:

class ParentClass{

//Parent class constructor

ParentClass(){

System.out.println("Constructor of Parent");

void disp(){

System.out.println("Parent Method");

class JavaExample extends ParentClass{

JavaExample(){

System.out.println("Constructor of Child");

void disp(){

System.out.println("Child Method");
//Calling the disp() method of parent class

super.disp();

public static void main(String args[]){

//Creating the object of child class

JavaExample obj = new JavaExample();

obj.disp();

The output is :

Constructor of Parent

Constructor of Child

Child Method

Parent Method

Inheritance in Java and types of Inheritance in Java


By

 Great Learning Team

 -

May 27, 2021

3685

Share
When a class is declared, with its specification, and the other sub-class members
will want to use its member methods(functions); that’s when they will go for
inheritance concepts. Inheritance concepts are everywhere in Java programming.

It’s impossible to write java programs without using inheritance. 

 What is Inheritance in Java?


 Why use Inheritance?  
 Terms Used in Inheritance  
 Types of Inheritance in Java  
 Inheritance Program in Java
 Method Overriding in Java
 Super Keyword in Java
 Why Multiple Inheritance is not supported in Java?

What is Inheritance in Java? 

Inheritance in Java Definition:

Inheritance in Java is a concept that acquires the properties from one class to other
classes; for example, the relationship between father and son. 

In Java, a class can inherit attributes and methods from another class. The class
that inherits the properties is known as the sub-class or the child class. The class
from which the properties are inherited from is know as the superclass or the parent
class.

In Inheritance, the properties of the base class is acquired by the derived classes.
Inheritance Syntax in Java:
1 class derived_class extends base_class 

2 { 

3    //methods

4    //fields

}
5

General format for Inheritance 


1
class superclass
2
{
3  // superclass data variables

4  // superclass member functions

5 }

6 class subclass extends superclass

7 {

 // subclass data variables


8
 // subclass member functions
9
}
10
Inheritance uses the “extends” keyword to create a derived class by reusing base
class code. 

Extends keyword in Java:

The extends keyword extends a class and is an indicator that a class is being
inherited by another class. When you say class B extends a class A, it means that
class B is inheriting the properties(methods, attributes) from class A. Here, class A
is the superclass or parent class and class B is the sub-class or child class.

Program Example: 
1 class Base

2  {

 public void M1()


3
 {
4
 System.out.println(“ Base Class Method ”);
5
 }
6
 }
7
class Derived extends Base
8 {

9  public void M2()

10  {

11  System.out.printIn(“ Derived Class Methods “);

12  }

}
13
class Test
14
{
15
16
 public static void main(String[] args)
17
 {
18
 Derived d = new Derived(); // creating object
19
 d.M1(); // print Base Class Method
20
 d.M2(); // print Derived Class Method
21
 }
22 }

23

Output:

Why use Inheritance? 


The main advantage of inheritance is code reusability and also method overriding
(runtime polymorphism). 

Inheritance is also known as the IS-A relationship. 

Terms Used in Inheritance 


Class: A class is a collection of objects which have common properties. 

Derived Class/Sub-class: Derived class is a class that inherits from a base class. It
is also known as subclass or child class. 
Base Class/Superclass: The base class is the main class where derived classes
inherit the features. It is also known as the superclass or parent class. 

Reusability: The name itself says reuse the repeated code in the programs. It is a
mechanism to reuse existing code when you are creating new classes. 

Types of Inheritance in Java 


The different types of Inheritance are:

 Single Inheritance
 Multiple Inheritance
 Multi-Level Inheritance
 Hierarchical Inheritance
 Hybrid Inheritance

Single Inheritance 

Creating subclasses from a single base class is called single inheritance. 

Figure: Single Inheritance

In Inheritance, we can access superclass methods and variables. We can also access
subclass methods and variables through subclass objects only. We have to take care
of superclass and subclass methods, and variable’s names shouldn’t conflict. 
Program Example: 
1 class A

2 {

 int a, b;
3
 void display()
4
 {
5
 System.out.println(“Inside class A values =”+a+” ”+b);
6
 }
7
}
8 class B extends A

9 {

10  int c;

11  void show()

12  {

 System.out.println(“Inside Class B values=”+a+” “+b+” “+c);  }


13
}
14
class SingleInheritance
15
{
16
 public static void main(String args[])
17
{
18
 B obj = new B(); //derived class object
19  obj.a=10;

20  obj.b=20;

21  obj.c=30;

22  obj.display();

 obj.show();
23
 }
24
25

26 }

27

Output:

Multiple Inheritance in Java: 

Defining derived class from numerous base classes is known as ‘Multiple


Inheritance’. In this case, there is more than one superclass, and there can be one or
more subclasses. 

Multiple inheritances are available in object-oriented programming with C++, but


it is not available in Java. 

Java developers want to use multiple inheritances in some cases. Fortunately, Java
developers have interface concepts expecting the developers to achieve multiple
inheritances by using multiple interfaces. 

Ex: class Myclass implements interface1, interface2,…. 


Multilevel Inheritance in Java:

In Multi-Level Inheritance in Java, a class extends to another class that is already


extended from another class. For example, if there is a class A that extends class B
and class B extends from another class C, then this scenario is known to follow
Multi-level Inheritance.

We can take an example of three classes, class Vehicle, class Car and class SUV.
Here, the class Vehicle is the grandfather class. The class Car extends class
Vehicle and class SUV extends class Car.
Hierarchical Inheritance in Java:

In Hierarchical Inheritance in Java, more than one derived class extend a single
base class. In simple words, more than one child class extend a single parent class
or a single parent class has more than one child classes.

For example, consider a parent class Car. Now, consider child classes Audi, BMW
and Mercedes. In Hierarchical Inheritance in Java, class Audi, class BMW and
class Mercedes, all these three extend class Car.
Hybrid Inheritance in Java: 

Hybrid Inheritance in Java is a combination of Inheritances. In this type of


Inheritance, more than one kind of inheritance is observed. For example, if we
have class A and class B that extend class C and then there is another class D that
extends class A, then this type of Inheritance is known as Hybrid Inheritance.

Why? Because we clearly observe that there is two kinds of inheritance here-
Hierarchical and Single Inheritance.

In the diagram shown below, we see another example of Hybrid Inheritance.

Inheritance Program in Java 


1. If we want to call methods and variables using the Parent class object,
you will get an error. 

Inheritance  Example in Java-1:


1 class Parent
2

3 {

 public void M1()


4
 {
5
 System.out.println("Parent Class Method");
6
 }
7
}
8
class Child extends Parent
9
{
10  public void M2()

11  {

12  System.out.println("Child Class Method");

13  }

14 }

class Inh_In_Java
15
{
16
 public static void main(String[] args)
17
 {
18
  Parent p=new Parent();
19
  p.M1();
20   p.M2(); // error-wrong way to call derived class method

21  }

22 }

23
Output: 

2. Creating object will be very important 

Parent p=new Child(); // will not work 

Inheritance  Example in Java-2:


1 class Parent

2 {

 public void M1()


3
 {
4
 System.out.println("Parent Class Method");
5
 }
6
}
7
class Child extends Parent
8 {

9  public void M2()

10  {

11  System.out.println("Child Class Method");

12  }

}
13
class Inh_In_Java
14
{
15
 public static void main(String[] args)
16

17  {

18   Parent p=new Child();

19   p.M1();

20   p.M2();

21  }

}
22

23

Output: 

3. Child p=new Parent(); 

This implementation will not work because of incompatible types:  It is not


possible to convert a Parent to a Child 

Inheritance  Example in Java-3: 


1 class Parent

2 {

 public void M1()


3
 {
4
 System.out.println("Parent Class Method");
5
 }
6
}
7

8 class Child extends Parent

9 {

10  public void M2()

11  {

 System.out.println("Child Class Method");


12
 }
13
}
14
class Inh_In_Java
15
{
16
 public static void main(String[] args)
17
 {
18  Child p=new Parent();

19  p.M1();

20  p.M2();

21  }

}
22

23

Output: 

4. From the above three examples, we understand that inheritance will be useful
when derived class objects call base class(parent class or superclass) methods and
variables. It will not throw an error. 
Inheritance  Example in Java-4: 
1

2 class Parent

3 {

 public void M1()


4
 {
5
 System.out.println("Parent Class Method");
6
 }
7
}
8
class Child extends Parent
9
{
10  public void M2()

11  {

12  System.out.println("Child Class Method");

13  }

}
14
class Inh_In_Java
15
{
16
 public static void main(String[] args)
17
 {
18
 Child p=new Child();
19
 p.M1();
20  p.M2();

21  }

22 }

23
Output:

Method Overriding in Java:

If the child class has the same method in its implementation as that of its parents
class, then the concept of method overriding comes into play.

In method overriding, the child class has the same method as that of the parent
class. The main use of this is to achieve runtime polymorphism.

Method Overriding is used to provide specific implementation of a particular


method which was provided by the parents class.

Rules for Method overriding are:

 Methods must share the same name in child and parent class.
 It must have the same parameter as in the superclass.
 There must be an IS-A type of Inheritance.

Super keyword in Java: 

Super keyword usage in inheritance, always refers to its immediate as an object. 

There are three usages of super keyword in Java: 

1. We can invoke the superclass variables. 

2. We can invoke the superclass methods. 


3. We can invoke the superclass constructor. 

Example for Super Keyword in Java: 


1 class Superclass

2 {

 int i =20;
3
void display()
4
{
5
 System.out.println(“Superclass display method”);
6
 }
7
}
8 class Subclass extends Superclass

9 {

10  int i = 100;

11  void display()

12  {

 super.display();
13
 System.out.println(“Subclass display method”);
14
 System.out.println(“ i value =”+i);
15
 System.out.println(“superclass i value =”+super.i);
16
 }
17
}
18 class SuperUse

19 {

20  public static void main(String args[])

21 {

22  Subclass obj = new Subclass();


23

24  obj.display();

25 }

26 }

27

Output: 

Why Multiple Inheritance is not supported in Java?


Let’s consider a case in Inheritance. Consider a class A, class B and class C. Now,
let class C extend class A and class B. Now, consider a method read() in both class
A and class B. The method read() in class A is different from the method read() in
class B. But, while inheritance happens, the compiler has difficulty in deciding on
which read() to inherit. So, in order to avoid such kind of ambiguity, multiple
inheritance is not supported in Java.

You might also like