0% found this document useful (0 votes)
24 views10 pages

Java Inheritance Examples and Types

The document explains the concept of inheritance in object-oriented programming, detailing how subclasses inherit properties and methods from superclasses. It covers various types of inheritance including single, hierarchical, multilevel, hybrid, and mentions the limitations of multiple inheritance in Java. Additionally, it provides example programs to illustrate each type of inheritance and the use of the 'super' keyword to access parent class methods and constructors.

Uploaded by

p38981094
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)
24 views10 pages

Java Inheritance Examples and Types

The document explains the concept of inheritance in object-oriented programming, detailing how subclasses inherit properties and methods from superclasses. It covers various types of inheritance including single, hierarchical, multilevel, hybrid, and mentions the limitations of multiple inheritance in Java. Additionally, it provides example programs to illustrate each type of inheritance and the use of the 'super' keyword to access parent class methods and constructors.

Uploaded by

p38981094
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

Module-2:

Inheritance:
A new class (called a subclass or child class) inherit the properties (fields) and
behaviors (methods) of an existing class (called a superclass or parent class) is called
inheritance.
Parent class: The class whose properties and behaviors inherited.
Child class: The class inherite the properties and behaviors from base class.

Use of Inheritance:
 Reuse code from the parent class.
 Add its own specific fields and methods.
 Override methods from the parent class to provide its own implementation.
Syntax:
class parentclass{
//methods and fields;
}
Class childclass extends parentclass{
//methods and fields;
}

Types of inheritance:
1. Single Inheritance
2. Hierarchal Inheritance
3. Multilevel Inheritance
4. Hybrid Inheritance
5. Multiple Inheritance
1. Single Inheritance: One class inherits from a single base class.

Example: Class A inherits from class B.

Example program for single inheritance:


// Base Class: Vehicle
class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Colour: " + colour);
[Link]("Fuel Type: " + fuelType);
[Link]("Speed: " + speed + " km/h");
}
}

// Child Class: Car


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
[Link]("Wheels: " + wheels);
[Link]("This car can carry 6 passengers.");
}
}

public class SingleInheritanceExample {


public static void main(String[] args) {
Car car = new Car();
[Link] = "Toyota";
[Link] = "Red";
[Link] = "Petrol";
[Link] = 120;
[Link] = 4;

// Display car information


[Link]();
}
}
Output:
Brand: Toyota
Colour: Red
Fuel Type: Petrol
Speed: 120 km/h
Wheels: 4
This car can carry 6 passengers.

2. Hierarchical Inheritance: Multiple classes inherit from a single base class.


Example: Class B, C and class D are inherit from class A.

Example Program for hierarchal Inheritance:


class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Colour: " + colour);
[Link]("Fuel Type: " + fuelType);
[Link]("Speed: " + speed + " km/h");
}
}

// Child Class 1: Car


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
[Link]("Wheels: " + wheels);
[Link]("This car can carry 6 passengers.");
}
}

// Child Class 2: Bike


class Bike extends Vehicle {
boolean hasHelmet;

void displayBikeInfo() {
displayInfo();
[Link]("Has Helmet: " + hasHelmet);
[Link]("This bike can carry 2 passengers.");
}
}

public class HierarchicalInheritanceExample {


public static void main(String[] args) {
// Creating an object of Car
Car car = new Car();
[Link] = "Honda";
[Link] = "Red";
[Link] = "Petrol";
[Link] = 150;
[Link] = 4;
[Link]();

// Creating an object of Bike


Bike bike = new Bike();
[Link] = "Yamaha";
[Link] = "Blue";
[Link] = "Electric";
[Link] = 100;
[Link] = true;
[Link]();
}
}
Output: Brand: Honda
Colour: Red
Fuel Type: Petrol
Speed: 150 km/h
Wheels: 4
This car can carry 6 passengers.
Brand: Yamaha
Colour: Blue
Fuel Type: Electric
Speed: 100 km/h
Has Helmet: true
This bike can carry 2 passengers.

3. Multilevel Inheritance: A class inherits from a derived class, which in turn inherits from
a base class.

Example: Class C inherits from class B, and class B inherits from class A.

Example program for multilevel inheritance.


// Base Class: Vehicle
class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Colour: " + colour);
[Link]("Fuel Type: " + fuelType);
[Link]("Speed: " + speed + " km/h");
}
}

// Intermediate Class: Car (inherits from Vehicle)


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
[Link]("Wheels: " + wheels);
[Link]("This car can carry 6 passengers.");
}
}

// Child Class: ElectricCar (inherits from Car)


class ElectricCar extends Car {
int batteryCapacity;

void displayElectricCarInfo() {
displayCarInfo();
[Link]("Battery Capacity: " + batteryCapacity + " kWh");
[Link]("This electric car can carry 4 passengers.");
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
ElectricCar eCar = new ElectricCar();
[Link] = "Tesla";
[Link] = "Black";
[Link] = "Electric";
[Link] = 200;
[Link] = 4;
[Link] = 75;

// Display ElectricCar information


[Link]();
}
}
Output:
Brand: Tesla
Colour: Black
Fuel Type: Electric
Speed: 200 km/h
Wheels: 4
This car can carry 6 passengers.
Battery Capacity: 75 kWh
This electric car can carry 4 passengers.

4. Hybrid Inheritance: A combination of different types of inheritance (such as multilevel


and hierarchical inheritance combined).

Example program for hybrid inheritance.


// Base Class: Vehicle
class Vehicle {
String brand;
String colour;
String fuelType;
int speed;

void displayInfo() {
[Link]("Brand: " + brand);
[Link]("Colour: " + colour);
[Link]("Fuel Type: " + fuelType);
[Link]("Speed: " + speed + " km/h");
}
}

// Helper Class 1: PassengerCapacity


class PassengerCapacity {
void displayPassengerCapacity(String vehicleType) {
if ([Link]("Car")) {
[Link]("This car can carry 6 passengers.");
} else if ([Link]("Bike")) {
[Link]("This bike can carry 2 passengers.");
} else if ([Link]("Bus")) {
[Link]("This bus can carry 30 passengers.");
}
}
}

// Child Class 1: Car (inherits from Vehicle and uses PassengerCapacity)


class Car extends Vehicle {
int wheels;

void displayCarInfo() {
displayInfo();
[Link]("Wheels: " + wheels);
PassengerCapacity passengerCapacity = new PassengerCapacity();
[Link]("Car");
}
}

// Child Class 2: ElectricCar (inherits from Car)


class ElectricCar extends Car {
int batteryCapacity; // specific to electric cars

void displayElectricCarInfo() {
displayCarInfo();
[Link]("Battery Capacity: " + batteryCapacity + " kWh");
[Link]("This electric car can carry 6 passengers.");
}
}

// Child Class 3: Bike (inherits from Vehicle and uses PassengerCapacity)


class Bike extends Vehicle {
boolean hasHelmet;

void displayBikeInfo() {
displayInfo();
[Link]("Has Helmet: " + hasHelmet);
PassengerCapacity passengerCapacity = new PassengerCapacity();
[Link]("Bike");
}
}

// Child Class 4: Bus (inherits from Vehicle and uses PassengerCapacity)


class Bus extends Vehicle {
int seatingCapacity;

void displayBusInfo() {
displayInfo();
[Link]("Seating Capacity: " + seatingCapacity);
PassengerCapacity passengerCapacity = new PassengerCapacity();
[Link]("Bus");
}
}

public class HybridInheritanceExample {


public static void main(String[] args) {
// Creating an object of Car
Car car = new Car();
[Link] = "Toyota";
[Link] = "Red";
[Link] = "Petrol";
[Link] = 120;
[Link] = 4;
[Link]();

// Creating an object of ElectricCar


ElectricCar electricCar = new ElectricCar();
[Link] = "Tesla";
[Link] = "White";
[Link] = "Electric";
[Link] = 150;
[Link] = 4;
[Link] = 75;
[Link]();

// Creating an object of Bike


Bike bike = new Bike();
[Link] = "Yamaha";
[Link] = "Blue";
[Link] = "Electric";
[Link] = 80;
[Link] = true;
[Link]();

// Creating an object of Bus


Bus bus = new Bus();
[Link] = "Mercedes";
[Link] = "Yellow";
[Link] = "Diesel";
[Link] = 90;
[Link] = 30;
[Link]();
}
}
5. Multiple Inheritance (Java does not support multiple inheritance through classes, but it
can be achieved using interfaces):
 A class inherits from more than one class (Java does not allow multiple inheritance
through classes to avoid ambiguity, but it allows multiple inheritance through
interfaces).

Super keyword:

Key Points About super:

1. Access Parent Constructor: super() calls the constructor of the parent class.
2. Access Parent Methods: [Link]() calls a method from the parent class
(even if overridden).
3. Access Parent Fields: [Link] refers to a field in the parent class.

Example program:
// Parent class (superclass)
class Animal {
String name;

// Constructor of parent class


public Animal(String name) {
[Link] = name;
}

// Method to display animal name


public void display() {
[Link]("Animal Name: " + name);
}
}

// Child class (subclass)


class Dog extends Animal {

// Constructor of child class


public Dog(String name) {
// Using 'super' to call the constructor of the parent class (Animal)
super(name);
}

// Overriding display method to call parent method using 'super'


public void display() {
[Link](); // Calls the display method of the parent class
[Link](name + " is a Dog.");
}
}

// Main class to run the program


public class SuperKeywordExample {
public static void main(String[] args) {
Dog dog = new Dog("Buddy"); // Create a Dog object
[Link](); // Calls the display method of the Dog class
}
}

Common questions

Powered by AI

Single inheritance in Java involves a single subclass inheriting from only one superclass, emphasizing a direct parent-child relationship. For example, a 'Car' class extending a 'Vehicle' class showing basic code reuse and extension. On the other hand, hierarchical inheritance involves several subclasses inheriting from the same superclass. This approach not only allows multiple classes to share common features from a single parent class but also introduces the possibility of specialization in each subclass, as seen with 'Car' and 'Bike' both inheriting from 'Vehicle' .

The 'super' keyword can address method overriding issues by allowing a subclass to bypass its overridden method and invoke the original implementation from the superclass. For example, if a 'Dog' class extends an 'Animal' class, both having a 'display' method, using 'super.display()' within the 'Dog' class's 'display' method allows it to first execute the 'Animal' class's 'display' method before adding subclass-specific behavior, thus maintaining expected functionality from the parent class .

Hierarchical inheritance in Java occurs when multiple classes inherit from a single base class. This means one parent class has several child classes. An example of hierarchical inheritance is a situation where a class 'Vehicle' is extended by multiple classes such as 'Car' and 'Bike'. Each subclass inherits attributes like 'brand', 'colour', 'fuelType', and methods such as 'displayInfo()' from the 'Vehicle' class, but also includes its own specific fields and methods, like 'wheels' for 'Car' or 'hasHelmet' for 'Bike' .

Multilevel inheritance allows a class to derive from another derived class, forming a chain of inheritance. In Java, this is exemplified by a 'Vehicle' class, from which a 'Car' class inherits, and further, an 'ElectricCar' class inherits from 'Car'. This setup provides a refined abstraction and code reuse across multiple levels of inheritance, allowing each class to build upon and extend the functionalities of the preceding class. For example, 'ElectricCar' can reuse methods and fields from 'Vehicle' via 'Car' without direct inheritance from 'Vehicle' .

The main types of inheritance in object-oriented programming are single inheritance, hierarchical inheritance, multilevel inheritance, hybrid inheritance, and multiple inheritance. Single inheritance allows one class to inherit from a single base class. Hierarchical inheritance involves multiple classes inheriting from a single base class. Multilevel inheritance lets a class inherit from a derived class that is itself derived from another base class. Hybrid inheritance is a combination of different types of inheritance, like multilevel and hierarchical. Multiple inheritance involves a class inheriting from more than one class, which Java supports only through interfaces to avoid ambiguity. In Java, classes can extend only one class, but they can implement multiple interfaces, allowing for a form of multiple inheritance .

The 'super' keyword in Java is used in a subclass to refer to its immediate parent class's methods and fields. Its primary uses are: calling a parent class constructor using 'super()', accessing a method in the parent class when it has been overridden in the child class using 'super.methodName()', and accessing a field in the parent class using 'super.fieldName'. This mechanism allows a subclass to leverage or explicitly invoke its parent class's features .

A helper class in hybrid inheritance provides supporting functionality without being a direct part of the inheritance hierarchy. In the context of hybrid inheritance in Java, for instance, the 'PassengerCapacity' class can be used by different subclasses like 'Car', 'Bike', and 'Bus' to handle passenger-related functions. This arrangement allows shared methods to be utilized across various subclasses without duplicating code, promoting composition over inheritance for some functionalities .

Hybrid inheritance combines two or more types of inheritance, such as combining both hierarchical and multilevel inheritance structures. This approach can create complex inheritance hierarchies that are more versatile but also result in complications like the Diamond Problem, where ambiguity arises when a class can inherit from a single class via multiple paths. Java does not support hybrid inheritance directly through classes to avoid these issues but supports it implicitly through a combination of classes and interfaces .

The benefits of multilevel inheritance include code reuse across multiple levels, which enhances maintainability and reduces redundancy by allowing each derived class to build upon its ancestors' code. It also supports clear abstraction layers. However, potential pitfalls include increased complexity in understanding and managing the inheritance chain, potential for tight coupling and fragile code, and the risk of unintended side effects if one class in the chain is modified. Ensuring proper protection and interface design can mitigate such risks .

Java uses interfaces to simulate multiple inheritance, allowing a class to implement multiple interfaces. While classes in Java cannot inherit from more than one class due to ambiguity concerns in multiple inheritance, implementing multiple interfaces enables a class to inherit behavior from several sources. Interfaces can declare methods without implementing them, and any class that implements an interface must provide implementations for its methods, thereby achieving similar outcomes to multiple inheritance .

You might also like