Akrb 1
Akrb 1
Inheritance allows a class (called the "subclass" or "child class") to acquire the properties and
behaviors of another class (called the "superclass" or "parent class"). This relationship is often
described as an "is-a" relationship, where the subclass "is a type of" the superclass.
SYNTAX:
class ParentClass {
CODE:
// Superclass
class Vehicle {
this.speed = speed;
this.fuel = fuel;
// Subclass
class Car extends Vehicle {
this.brand = brand;
myCar.displayCarInfo();
}
Explanation of the Code
1. Superclass (Vehicle): This class has two fields, speed and fuel, and a method displayInfo() that prints
these attributes. The protected keyword allows subclasses to access these fields directly.
2. Subclass (Car): The Car class extends Vehicle, inheriting its fields and methods. Car has an additional
field brand and a method displayCarInfo() that first calls displayInfo() from the superclass to print
speed and fuel, then prints the car brand.
3. Main Class: We create an instance of Car and call its displayCarInfo() method, which outputs both the
vehicle's basic information and the car-specific brand.
OUT PUT:
Fuel: 50 liters
Brand: Toyota
Pros of Inheritance
1. Code Reusability: Common functionality can be defined once in the superclass and reused by subclasses.
2. Simplifies Code: Reduces code duplication, making programs shorter and easier to manage.
3. Logical Structure: Encourages a hierarchical structure, which helps organize related classes and makes the design
more intuitive.
4. Extendability: New functionality can be added to existing code by creating subclasses, promoting scalability.
Cons of Inheritance
1. Tight Coupling: Subclasses are dependent on the superclass, making it difficult to make changes in the superclass
without affecting subclasses.
2. Increased Complexity: Deep inheritance hierarchies can make the code hard to follow and understand.
3. Limited Flexibility: A subclass can only inherit from one superclass in Java (single inheritance), which can be
restrictive.
4. Potential for Misuse: If inheritance is used where it isn’t appropriate (like when the "is-a" relationship doesn’t
hold), it can lead to code that is difficult to maintain or understand.
BLOCK DIAGRAM:
REAL TIME:
In banking systems, inheritance is often used to model different types of bank accounts. Here’s a
hierarchy you might see:
Superclass: Account