0% found this document useful (0 votes)
7 views

JAVA Inheritance

Inheritance in Java allows one class to acquire properties and behaviors from another, facilitating code reusability and method overriding. It establishes an IS-A relationship between classes, with types including single, multilevel, and hierarchical inheritance, while multiple inheritance is only supported through interfaces. The document provides examples and explanations of different inheritance types, their syntax, and the rationale behind Java's design choices regarding inheritance.

Uploaded by

gopogo56
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

JAVA Inheritance

Inheritance in Java allows one class to acquire properties and behaviors from another, facilitating code reusability and method overriding. It establishes an IS-A relationship between classes, with types including single, multilevel, and hierarchical inheritance, while multiple inheritance is only supported through interfaces. The document provides examples and explanations of different inheritance types, their syntax, and the rationale behind Java's design choices regarding inheritance.

Uploaded by

gopogo56
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that we can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java


Advertisement

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template
or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits
the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class.
You can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
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.

In the terminology of Java, a class which is inherited is called a parent or superclass,


and the new class is called child or subclass.

Java Inheritance Example


As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. The relationship between the two classes is Programmer IS-A Employee. It
means that Programmer is a type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }

Programmer salary is:40000.0


Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.

Note: Multiple inheritance is not supported in Java through class.


When one class inherits multiple classes, it is known as multiple inheritance. For
Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example
given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can
see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example
When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

File: TestInheritance3.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }

Compile Time Error

Inheritance in Java Example


Example: In the below example of inheritance, class Bicycle is a base
class, class MountainBike is a derived class that extends the Bicycle class
and class Test is a driver class to run the program.

// Java program to illustrate the

// concept of inheritance

// base class

class Bicycle {

// the Bicycle class has two fields

public int gear;

public int speed;

// the Bicycle class has one constructor

public Bicycle(int gear, int speed)

this.gear = gear;

this.speed = speed;

// the Bicycle class has three methods

public void applyBrake(int decrement)

speed -= decrement;
}

public void speedUp(int increment)

speed += increment;

// toString() method to print info of Bicycle

public String toString()

return ("No of gears are " + gear + "\n"

+ "speed of bicycle is " + speed);

// derived class

class MountainBike extends Bicycle {

// the MountainBike subclass adds one more field

public int seatHeight;

// the MountainBike subclass has one constructor

public MountainBike(int gear, int speed,

int startHeight)

// invoking base-class(Bicycle) constructor

super(gear, speed);

seatHeight = startHeight;

// the MountainBike subclass adds one more method


public void setHeight(int newValue)

seatHeight = newValue;

// overriding toString() method

// of Bicycle to print more info

@Override public String toString()

return (super.toString() + "\nseat height is "

+ seatHeight);

// driver class

public class Test {

public static void main(String args[])

MountainBike mb = new MountainBike(3, 100, 25);

System.out.println(mb.toString());

Output
No of gears are 3
speed of bicycle is 100
seat height is 25
Example 2: In the below example of inheritance, class Employee is a
base class, class Engineer is a derived class that extends the Employee
class and class Test is a driver class to run the program.
Java
// Java Program to illustrate Inheritance (concise)

import java.io.*;

// Base or Super Class


class Employee {
int salary = 60000;
}

// Inherited or Sub Class


class Engineer extends Employee {
int benefits = 10000;
}

// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salary
+ "\nBenefits : " + E1.benefits);
}
}

Output
Salary : 60000
Benefits : 10000
Illustrative image of the program:
In practice, inheritance, and polymorphism are used together in Java to
achieve fast performance and readability of code.

Java Inheritance Types


Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
1. Multilevel Inheritance
1. Hierarchical Inheritance
1. Multiple Inheritance
1. Hybrid Inheritance

1. Single Inheritance

In single inheritance, a sub-class is derived from only one super class. It


inherits the properties and behaviour of a single-parent class. Sometimes,
it is also known as simple inheritance. In the below figure, ‘A’ is a parent
class and ‘B’ is a child class. The class ‘B’ inherits all the properties of the
class ‘A’.

Single inheritance

Java
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;
// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}

class Two extends One {


public void print_for() { System.out.println("for"); }
}

// Driver class
public class Main {
// Main function
public static void main(String[] args)
{
Two g = new Two();
g.print_geek();
g.print_for();
g.print_geek();
}
}

Output
Geeks
for
Geeks

2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class,
and as well as the derived class also acts as the base class for other
classes. In the below image, class A serves as a base class for the
derived class B, which in turn serves as a base class for the derived class
C. In Java, a class cannot directly access the grandparent’s members.
Multilevel Inheritance

Java
// Importing required libraries
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class One


class One {
// Method to print "Geeks"
public void print_geek() {
System.out.println("Geeks");
}
}

// Child class Two inherits from class One


class Two extends One {
// Method to print "for"
public void print_for() {
System.out.println("for");
}
}

// Child class Three inherits from class Two


class Three extends Two {
// Method to print "Geeks"
public void print_lastgeek() {
System.out.println("Geeks");
}
}
// Driver class
public class Main {
public static void main(String[] args) {
// Creating an object of class Three
Three g = new Three();

// Calling method from class One


g.print_geek();

// Calling method from class Two


g.print_for();

// Calling method from class Three


g.print_lastgeek();
}
}

Output
Geeks
for
Geeks

3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class)
for more than one subclass. In the below image, class A serves as a base
class for the derived classes B, C, and D.

Java
// Java program to illustrate the
// concept of Hierarchical inheritance

class A {
public void print_A() { System.out.println("Class A"); }
}

class B extends A {
public void print_B() { System.out.println("Class B"); }
}

class C extends A {
public void print_C() { System.out.println("Class C"); }
}

class D extends A {
public void print_D() { System.out.println("Class D"); }
}

// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

Output
Class A
Class B
Class A
Class C
Class A
Class D

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass
and inherit features from all parent classes. Please note that Java
does not support multiple inheritances with classes. In Java, we can
achieve multiple inheritances only through Interfaces. In the image below,
Class C is derived from interfaces A and B.

Multiple Inheritance

Java
// Java program to illustrate the
// concept of Multiple inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

interface One {
public void print_geek();
}

interface Two {
public void print_for();
}

interface Three extends One, Two {


public void print_geek();
}
class Child implements Three {
@Override public void print_geek()
{
System.out.println("Geeks");
}

public void print_for() { System.out.println("for"); }


}
// Drived class
public class Main {
public static void main(String[] args)
{
Child c = new Child();
c.print_geek();
c.print_for();
c.print_geek();
}
}

Output
Geeks
for
Geeks

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java
doesn’t support multiple inheritances with classes, hybrid inheritance
involving multiple inheritance is also not possible with classes. In Java, we
can achieve hybrid inheritance only through Interfaces if we want to
involve multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not
necessarily require the use of Multiple Inheritance exclusively. It can be
achieved through a combination of Multilevel Inheritance and Hierarchical
Inheritance with classes, Hierarchical and Single Inheritance with classes.
Therefore, it is indeed possible to implement Hybrid inheritance using
classes alone, without relying on multiple inheritance type.
Hybrid Inheritance

Java IS-A type of Relationship


IS-A is a way of saying: This object is a type of that object. Let us see how
the extends keyword is used to achieve inheritance.
Java

public class SolarSystem {


}
public class Earth extends SolarSystem {
}
public class Mars extends SolarSystem {
}
public class Moon extends Earth {
}
Now, based on the above example, in Object-Oriented terms, the
following are true:-
 SolarSystem is the superclass of Earth class.
 SolarSystem is the superclass of Mars class.
 Earth and Mars are subclasses of SolarSystem class.
 Moon is the subclass of both Earth and SolarSystem classes.
Java

class SolarSystem {
}
class Earth extends SolarSystem {
}
class Mars extends SolarSystem {
}
public class Moon extends Earth {
public static void main(String args[])
{
SolarSystem s = new SolarSystem();
Earth e = new Earth();
Mars m = new Mars();

System.out.println(s instanceof SolarSystem);


System.out.println(e instanceof Earth);
System.out.println(m instanceof SolarSystem);
}
}

Output
true
true
true
What Can Be Done in a Subclass?
In sub-classes we can inherit members as is, replace them, hide them, or
supplement them with new members:
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the
superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the same
signature as the one in the superclass, thus overriding it (as in the
example above, toString() method is overridden).
 We can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the
superclass.
 We can write a subclass constructor that invokes the constructor of the
superclass, either implicitly or by using the keyword super.
Advantages Of Inheritance in Java:
1. Code Reusability: Inheritance allows for code reuse and reduces the
amount of code that needs to be written. The subclass can reuse the
properties and methods of the superclass, reducing duplication of
code.
1. Abstraction: Inheritance allows for the creation of abstract classes that
define a common interface for a group of related classes. This
promotes abstraction and encapsulation, making the code easier to
maintain and extend.
1. Class Hierarchy: Inheritance allows for the creation of a class
hierarchy, which can be used to model real-world objects and their
relationships.
1. Polymorphism: Inheritance allows for polymorphism, which is the ability
of an object to take on multiple forms. Subclasses can override the
methods of the superclass, which allows them to change their behavior
in different ways.
Disadvantages of Inheritance in Java:
1. Complexity: Inheritance can make the code more complex and harder
to understand. This is especially true if the inheritance hierarchy is
deep or if multiple inheritances is used.
1. Tight Coupling: Inheritance creates a tight coupling between the
superclass and subclass, making it difficult to make changes to the
superclass without affecting the subclass.
Conclusion
Let us check some important points from the article are mentioned below:
 Default superclass: Except Object class, which has no superclass,
every class has one and only one direct superclass (single
inheritance). In the absence of any other explicit superclass, every
class is implicitly a subclass of the Object class.
 Superclass can only be one: A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is
because Java does not support multiple inheritances with classes.
Although with interfaces, multiple inheritances are supported by Java.
 Inheriting Constructors: 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.
 Private member inheritance: A subclass does not inherit the private
members of its parent class. However, if the superclass has public or
protected methods(like getters and setters) for accessing its private
fields, these can also be used by the subclass.

FAQs in Inheritance
1. What is Inheritance Java?
Inheritance is a concept of OOPs where one class inherits from another
class that can reuse the methods and fields of the parent class.
2. What are the 4 types of inheritance in Java?
There are Single, Multiple, Multilevel, Hierarchical and Hybrid
3. What is the use of extend keyword?
Extend keyword is used for inheriting one class into another.
4. What is an example of inheritance in Java?
A real-world example of Inheritance in Java is mentioned below:
Consider a group of vehicles. You need to create classes for Bus, Car,
and Truck. The methods fuelAmount(), capacity(), applyBrakes() will be
the same for all three classes.

You might also like