Inheritance
A class can inherit from another with extends, automatically getting access to its fields and methods. super(name) inside a subclass's constructor calls the parent class's constructor, which is required before the subclass constructor can do anything else when the parent has no no-argument constructor.
Overriding with @Override
Marking a method @Override tells the compiler you intend to replace the parent class's version — it's optional, but it catches real mistakes, like a typo'd method name that would otherwise silently define a brand-new method instead of overriding the one you meant to. dog.speak() calls Dog's own version, not Animal's, because Dog overrides it.
public class Main {
static class Animal {
String name;
Animal(String name) {
this.name = name;
}
String speak() {
return name + " makes a sound";
}
}
static class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
String speak() {
return name + " barks";
}
}
public static void main(String[] args) {
Dog dog = new Dog("Rex");
System.out.println(dog.speak());
}
}Rex barks
Next: polymorphism and interfaces — Java's first-class way of describing shared behavior across unrelated classes.
Practice exercise
Define a class Animal with a field name and a method speak() returning name + " makes a sound". Define a class Cat that extends Animal and overrides speak() to return name + " meows". Create a Cat named "Whiskers" and print its speak().