java
  1. java-inheritance

Java Inheritance

Syntax

class ChildClass extends ParentClass {
    // child class code
}

Example

Here is an example of inheritance in Java:

class Animal {
    public void makeSound() {
        System.out.println("The animal makes a sound");
    }
}

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

public class Main {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.makeSound();
        
        Dog myDog = new Dog();
        myDog.makeSound();
    }
}

Output

The animal makes a sound
The dog barks

Explanation

Inheritance is a mechanism in Java that allows a class to inherit properties and methods from another class. The class that inherits is called the child class, and the class being inherited from is called the parent class.

To create a child class that inherits from a parent class, we use the extends keyword followed by the name of the parent class. The child class can then access the properties and methods of the parent class, as well as add its own.

In the example above, the Dog class inherits from the Animal class. It overrides the makeSound() method of the parent class to specify that a dog barks. When we create an instance of the Dog class and call its makeSound() method, it prints "The dog barks".

Use

Inheritance is used in Java to reuse code and create hierarchies of classes. It allows us to build on existing code and create specialized versions of existing classes.

Important Points

  • Inheritance allows a class to inherit properties and methods from another class.
  • The class being inherited from is called the parent class, and the class that inherits is called the child class.
  • In Java, we use the extends keyword to denote inheritance.
  • A child class can access the properties and methods of the parent class, as well as add its own.
  • Inheritance allows for code reuse and the creation of hierarchies of classes.

Summary

Inheritance is a powerful mechanism in Java that allows classes to inherit properties and methods from other classes. It is used to create hierarchies of classes and reuse existing code. In Java, we use the extends keyword to denote inheritance, and a child class can access the properties and methods of the parent class, as well as add its own.

Published on: