Have a question?
Message sent Close
View Categories

What is Java Inheritance?

What is Java Inheritance?

📄
filename.js
class Superclass {

    // Fields (variables)

    // Methods

}

class Subclass extends Superclass {

    // Additional fields (variables)

    // Additional methods or overriding methods

}

📄
filename.js
// Superclass

class Animal {

    void eat() {

        System.out.println("This animal eats food.");

    }

}

// Subclass

class Dog extends Animal {

    void bark() {

        System.out.println("The dog barks.");

    }

}

public class Main {

    public static void main(String[] args) {

        Dog myDog = new Dog();

        myDog.eat(); // Inherited method

        myDog.bark(); // Subclass-specific method

    }

}

📄
filename.js
// Base class

class Animal {

    void eat() {

        System.out.println("This animal eats food.");

    }

}

// Intermediate class

class Mammal extends Animal {

    void breathe() {

        System.out.println("This mammal breathes air.");
    }

}


// Derived class

class Dog extends Mammal {

    void bark() {

        System.out.println("The dog barks.");

    }

}

public class Main {

    public static void main(String[] args) {

        Dog myDog = new Dog();

        myDog.eat(); // Inherited from Animal

        myDog.breathe(); // Inherited from Mammal

        myDog.bark(); // Dog-specific method

    }

}
📄
filename.js
// Superclass

class Animal {

    void eat() {

        System.out.println("This animal eats food.");

    }

}

// Subclass 1

class Dog extends Animal {

    void bark() {

        System.out.println("The dog barks.");

    }

}

// Subclass 2

class Cat extends Animal {

    void meow() {

        System.out.println("The cat meows.");

    }

}
public class Main {

    public static void main(String[] args) {

        Dog myDog = new Dog();

        Cat myCat = new Cat();

        myDog.eat(); // Inherited method

        myDog.bark(); // Dog-specific method

        myCat.eat(); // Inherited method

        myCat.meow(); // Cat-specific method

    }

}