#JavaDay24

Опубликовано: 16 Март 2026
на канале: Geeks With Geeks
14
1

Java inheritance allows a class to inherit properties and behaviors (methods) from another class, known as the superclass or parent class. The class that inherits from the superclass is called the subclass or child class. Inheritance promotes code reuse and establishes a hierarchical relationship between classes.

In Java, inheritance is implemented using the `extends` keyword. The subclass can access the public and protected members (fields and methods) of the superclass. It can also override the superclass methods to provide its own implementation or add new methods and fields.

Key concepts of Java inheritance include:

1. *Superclass and Subclass:* The superclass is the existing class from which properties and behaviors are inherited. The subclass is the new class that extends the superclass.

2. *Single Inheritance:* Java supports single inheritance, meaning a subclass can inherit from only one superclass. However, Java supports multiple levels of inheritance, where a class can be both a subclass and a superclass.

3. *Access Modifiers:* Inherited members of the superclass are subject to access control rules. Public members are accessible to all classes, protected members are accessible to subclasses and classes in the same package, and private members are accessible only within the class itself.

4. *Method Overriding:* Subclasses can override superclass methods to provide specialized behavior. This allows for polymorphism, where a subclass object can be treated as an instance of its superclass.

5. *Constructor Inheritance:* Constructors are not inherited by subclasses, but a subclass constructor implicitly invokes the superclass constructor using the `super()` keyword.

6. *`super` Keyword:* Used to access superclass members or invoke superclass constructors from within the subclass.

Example:

```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {
void sound() {
System.out.println("Dog barks");
}
}

public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Output: Dog barks
}
}
```

In this example, the `Dog` class inherits the `sound()` method from the `Animal` class and overrides it to provide its own implementation.