Inheritance

Inheritance in Java

public class Animal {
    String name;

    public void setName(String name) {
        this.name = name;
    }
}

public class Dog extends Animal {
    public void sleep() {
        System.out.println(name + " zzz");
    }

    public static void main(String[] args) {
        Dog dog = new Dog();
        dog.setName("puppy");
        dog.sleep();
    }
}

IS-A Relationship

Animal dog = new Dog();
Dog dog = new Animal(); // Compile error: An object created from the parent class cannot be used as the type of the child class.

Method Overriding

public class HouseDog extends Dog {
    public void sleep() {
        System.out.println(name + " zzz in house");
    }

    public static void main(String[] args) {
        HouseDog houseDog = new HouseDog();
        houseDog.setName("yellow");
        houseDog.sleep();
    }
}
//yellow zzz in house

Method Overloading

Creating a method with the same name but different parameters.

public class HouseDog extends Dog {
    public void sleep() {
        System.out.println(name + " zzz in house");
    } // sleep method with no parameters
    public void sleep(int hour) {
        System.out.println(name + " zzz in house " + hour + "hours");
    } // sleep method with parameters

    public static void main(String[] args) {
        HouseDog houseDog = new HouseDog();
        houseDog.setName("yellow");
        houseDog.sleep();
        houseDog.sleep(3);
    }
}
//yellow zzz in house
//yellow zzz in house 3hours

💡 Inheritance is achieved through 'copying'.

Interface

An interface is a collection of abstract methods. The main purpose is to make classes independent of dependent classes.