Java inheritance


Inheritance is a key concept in object-oriented programming that allows you to create new classes based on existing classes. In Java, inheritance is implemented using the extends keyword. When a class extends another class, it inherits all the properties and methods of the parent class, and can also override or add its own properties and methods. Here’s an example of inheritance in Java:

// Parent class
public class Animal {
    private String name;
    private int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void eat() {
        System.out.println("The animal is eating");
    }

    public void sleep() {
        System.out.println("The animal is sleeping");
    }

    public void move() {
        System.out.println("The animal is moving");
    }
}

// Child class
public class Dog extends Animal {
    private String breed;

    public Dog(String name, int age, String breed) {
        super(name, age);
        this.breed = breed;
    }

    public void bark() {
        System.out.println("The dog is barking");
    }

    @Override
    public void move() {
        System.out.println("The dog is running");
    }
}

In this example, Animal is the parent class and Dog is the child class that extends Animal. Animal has three instance variables (name, age, and breed), a constructor that initializes these variables, and three instance methods (eat, sleep, and move). Dog also has an instance variable breed and a constructor that initializes all the variables using the super keyword to call the parent constructor. Dog also has a new instance method bark that is not present in the parent class, and overrides the move method of the parent class.

Now, let’s create an object of the Dog class and call its methods:

// Creating an object
Dog dog = new Dog("Max", 5, "Labrador");

// Accessing instance variables
String name = dog.getName();
int age = dog.getAge();
String breed = dog.getBreed();

// Calling instance methods
dog.eat();
dog.sleep();
dog.move();
dog.bark();

In this example, we create an object of the Dog class and call its methods using the dot notation. The eat, sleep, and move methods are inherited from the parent class, while the bark method is defined in the child class.

In summary, inheritance is a key concept in Java that allows you to create new classes based on existing classes. Inheritance allows you to reuse code and create a hierarchical class structure. To use inheritance in Java, you need to use the extends keyword to create a child class that inherits the properties and methods of a parent class. Understanding inheritance is essential to writing object-oriented programs in Java.

A quick recap of Java