Java one

 

1. Single Inheritance

One class inherits from one parent class.

class Animal {

    void sound() {

        System.out.println("Animal makes sound");

    }

}


class Dog extends Animal {

    void bark() {

        System.out.println("Dog barks");

    }

}

2. Multilevel Inheritance

A class inherits from a class, which itself inherits from another class.

class Animal {

    void eat() {

        System.out.println("Animal eats");

    }

}


class Dog extends Animal {

    void bark() {

        System.out.println("Dog barks");

    }

}


class Puppy extends Dog {

    void weep() {

        System.out.println("Puppy weeps");

    }

}

3. Hierarchical Inheritance

Multiple classes inherit from the same parent class.

class Animal {

    void sound() {

        System.out.println("Animal makes sound");

    }

}


class Dog extends Animal {

    void bark() {

        System.out.println("Dog barks");

    }

}


class Cat extends Animal {

    void meow() {

        System.out.println("Cat meows");

    }

}

4. Multiple Inheritance

interface A {
    void show();
}

interface B {
    void display();
}

class C implements A, B {
    public void show() {
        System.out.println("Show A");
    }
    public void display() {
        System.out.println("Display B");
    }
}

 5. Hybrid Inheritance
Hybrid Inheritance is a combination of multiple and multilevel inheritance.

interface A {
    void showA();
}

interface B {
    void showB();
}

class C implements A, B {
    public void showA() {
        System.out.println("A's method");
    }

    public void showB() {
        System.out.println("B's method");
    }
}

class D extends C {
    void showD() {
        System.out.println("D's method");
    }
}

public class Main {
    public static void main(String[] args) {
        D obj = new D();
        obj.showA(); // from A
        obj.showB(); // from B
        obj.showD(); // from D
    }
}

Comments

Popular posts from this blog

Creative Writing 11

Note Making