Multilevel Inheritance

Multilevel Inheritance

Multilevel inheritance is a type of inheritance where a class is derived from another class, which in turn is derived from another class. This forms a hierarchy of inheritance where each class inherits properties and behaviors from its superclass.

Example:
class Animal {
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("The dog barks.");
    }
}

class Puppy extends Dog {
    void weep() {
        System.out.println("The puppy weeps.");
    }
}

public class Main {
    public static void main(String[] args) {
        Puppy puppy = new Puppy();
        puppy.eat();
        puppy.bark();
        puppy.weep();
    }
}

Program to Try
// Base class
class Shape {
    double length;
    double width;

    // Default constructor
    Shape() {
        length = 0;
        width = 0;
    }

    // Parameterized constructor
    Shape(double length, double width) {
        this.length = length;
        this.width = width;
    }

    // Method to display dimensions
    void displayDimensions() {
        System.out.println("Length: " + length + ", Width: " + width);
    }
}

// Derived class from Shape
class Rectangle extends Shape {
    // Default constructor
    Rectangle() {
        super();
    }

    // Parameterized constructor
    Rectangle(double length, double width) {
        super(length, width);
    }

    // Method to calculate the area of the rectangle
    double calculateArea() {
        return length * width;
    }
}

// Derived class from Rectangle
class Box extends Rectangle {
    double height;

    // Default constructor
    Box() {
        super();
        height = 0;
    }

    // Parameterized constructor
    Box(double length, double width, double height) {
        super(length, width);
        this.height = height;
    }

    // Method to calculate the volume of the box
    double calculateVolume() {
        return length * width * height;
    }

    // Method to display dimensions including height
    void displayDimensions() {
        super.displayDimensions();
        System.out.println("Height: " + height);
    }
}

// Main class to test the inheritance
public class Main {
    public static void main(String[] args) {
        // Create a Box object using the parameterized constructor
        Box box = new Box(5, 3, 4);

        // Display the dimensions
        System.out.println("Box Dimensions:");
        box.displayDimensions();

        // Calculate and display the area of the base (rectangle)
        System.out.println("Area of the base (rectangle): " + box.calculateArea());

        // Calculate and display the volume of the box
        System.out.println("Volume of the box: " + box.calculateVolume());
    }
}

Comments

Popular posts from this blog

KTU OOP LAB JAVA CSL 203 BTech CS S3 - Dr Binu V P

Syllabus and Practice Questions KTU OOPS Lab Java CSL 203

String Problems