Junior — Middle
Can you explain what subclasses in Java are and how they are used?
sobes.tech AI
Answer from AI
In Java, a subclass is a class that inherits properties and methods from another class, called the superclass or parent class. Subclasses allow creating more specialized versions of the base class, extending or overriding its functionality.
Using subclasses helps implement the inheritance principle, one of the key principles of object-oriented programming. This allows code reuse and the creation of class hierarchies.
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
}
}
In this example, the Dog class is a subclass of Animal and overrides the sound() method.