Assignment_9: - Programs on single, multilevel, and hierarchical inheritance.
Inheritance in Java
Inheritance in Java is a core OOP concept that allows a class to acquire properties and
behaviours from another class. It helps in creating a new class from an existing class,
promoting code reusability and better organization.
A subclass can reuse the fields and methods of the parent class without rewriting the
code
A subclass can add its own fields and methods or modify existing ones to extend
functionality.
Types of Inheritance in Java
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance.
Example: -
1. Single Inheritance
//Super class
class Vehicle
Vehicle ()
[Link]("This is a Vehicle");
// Subclass
class Car extends Vehicle
Car ()
[Link]("This Vehicle is Car");
public class Test
public static void main (String [] args)
// Creating object of subclass invokes base class constructor
Car obj = new Car ();
Output
This is a Vehicle
This Vehicle is Car
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.
Example: -
class Vehicle
Vehicle ()
[Link]("This is a Vehicle");
class FourWheeler extends Vehicle
FourWheeler()
[Link]("4 - Wheeler Vehicles");
class Car extends FourWheeler
Car ()
[Link]("This 4-Wheeler Vehicle is a Car");
public class Geeks
{
public static void main (String [] args)
Car obj = new Car (); // Triggers all constructors in order
Output
This is a Vehicle
4-Wheeler Vehicles
This 4-Wheeler Vehicle is a Car
3. Hierarchical Inheritance
In hierarchical inheritance, more than one subclass is inherited from a single base class. i.e.
more than one derived class is created from a single base class. For example, cars and buses
both are vehicle
class Vehicle
Vehicle ()
[Link]("This is a Vehicle");
class Car extends Vehicle
Car ()
[Link]("This Vehicle is Car");
}
}
class Bus extends Vehicle
Bus ()
[Link]("This Vehicle is Bus");
public class Test
public static void main (String [] args)
Car obj1 = new Car ();
Bus obj2 = new Bus ();
Output
This is a Vehicle
This Vehicle is Car
This is a Vehicle
This Vehicle is Bus