Junior — Middle
How to implement class inheritance in Java?
sobes.tech AI
Answer from AI
In Java, class inheritance is implemented using the keyword extends. One class (subclass) can inherit properties and methods from another class (superclass), which allows code reuse and functionality extension.
Example:
// Superclass
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
// Subclass inherits from Animal
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Outputs: Dog barks
}
}
It is important to remember that Java supports only single inheritance (a subclass can inherit from only one superclass).