Java Basics Inheritance

In Java, inheritance is a mechanism that allows one class to inherit properties and methods from another class. The class that inherits properties and methods is called a subclass or derived class, and the class that provides the properties and methods is called a superclass or base class. Here are some basics of inheritance in Java:

1. Declaration: To declare a class that inherits from another class in Java, you use the `extends` keyword followed by the name of the superclass. For example:

public class Student extends Person {
    int id;
}

This declares a class called `Student` that inherits from the `Person` class and adds an attribute `id`.

2. Superclass and subclass: The superclass is the class that is being inherited from, and the subclass is the class that is inheriting properties and methods. For example:

public class Person {
    String name;
}

public class Student extends Person {
    int id;
}

Here, `Person` is the superclass and `Student` is the subclass.

3. Inherited properties and methods: The subclass inherits all the public and protected properties and methods of the superclass. For example:

public class Person {
    public String name;
    protected int age;
}

public class Student extends Person {
    public int id;
}

Student student = new Student();
student.name = "John"; // inherited from Person
student.age = 25; // inherited from Person
student.id = 123; // own property

Here, the `Student` class inherits the `name` and `age` properties from the `Person` class, and adds its own property `id`.

4. Overriding methods: The subclass can override the methods of the superclass by defining a method with the same name and signature. For example:

public class Person {
    public void sayHello() {
        System.out.println("Hello!");
    }
}

public class Student extends Person {
    public void sayHello() {
        System.out.println("Hi there!");
    }
}

Person person = new Person();
person.sayHello(); // prints "Hello!"

Student student = new Student();
student.sayHello(); // prints "Hi there!"

Here, the `Student` class overrides the `sayHello` method of the `Person` class.

Inheritance is a powerful feature of object-oriented programming in Java, and it allows you to reuse code and create complex class hierarchies. By defining classes that inherit from other classes, you can create more specialized objects and add new functionality to existing classes.