Junior — Middle
How is class inheritance implemented in Java?
sobes.tech AI
Answer from AI
In Java, inheritance is implemented using the extends keyword. The subclass inherits all public and protected fields and methods from the superclass, enabling code reuse and extension.
Example:
class Animal {
void sound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound(); // Outputs: Bark
}
}
Java supports single inheritance of classes (one parent), but allows multiple inheritance through interfaces.