A class can extend another to reuse and specialise its behaviour.
public class Product {
protected String name;
protected double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String describe() {
return name + " — NPR " + price;
}
}
public class Book extends Product {
private String author;
public Book(String name, double price, String author) {
super(name, price); // must be the first statement
this.author = author;
}
@Override
public String describe() {
return super.describe() + " by " + author;
}
}Book b = new Book("Palpasa Cafe", 480, "Narayan Wagle");
System.out.println(b.describe());
// Palpasa Cafe — NPR 480 by Narayan Waglesuper
super(...)calls the parent constructor — required, and must come first.super.method()calls the parent's version of an overridden method.
@Override
Always write it. It is optional to the compiler but it catches typos — if the method doesn't actually override anything (wrong name, wrong parameters), you get a compile error instead of a silently-unused method.
Polymorphism
A variable of the parent type can hold any subclass, and the subclass version of the method runs:
Product p = new Book("Palpasa Cafe", 480, "Narayan Wagle");
System.out.println(p.describe()); // runs Book's versionThis is what makes it possible to write code against Product that works
for every kind of product, present and future.
Access modifiers
| Modifier | Same class | Same package | Subclass | Everywhere |
|---|---|---|---|---|
private |
yes | no | no | no |
| (default) | yes | yes | no | no |
protected |
yes | yes | yes | no |
public |
yes | yes | yes | yes |
Single inheritance
A Java class extends exactly one class. To share behaviour across unrelated hierarchies, use interfaces (next chapter).
final
public final class Config { } // cannot be extended
public final void save() { } // cannot be overriddenComposition over inheritance
Inheritance couples classes tightly. Before extending, ask whether the
relationship is really "is-a" — if it's "has-a", hold the other object as
a field instead. A Car has an Engine; it is not an Engine.