Inheritance declares an “is a” relationship: a subclass can be used where its parent type is expected. It also brings inherited behavior. Use it when that substitution is honest, not merely to avoid copying a few lines. Composition remains the default when one object simply needs another's services.
Work through the example
extends names the parent class. ReportItem deliberately has no final modifier so TimedItem can extend it; TimedItem is final to stop further subclassing. super(title) initializes the parent part before the child stores its own data. The parent keeps title private and exposes a method; the child uses that method instead of accessing the field directly.
Overriding replaces instance behavior for calls on the child object, including calls made through a parent-typed reference. @Override is useful evidence that the signature is correct. We do not add setters or weaken the parent's nonblank-title rule in the subclass: callers must still receive a valid ReportItem.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
public class Main {
public static void main(String[] args) {
ReportItem item = new TimedItem("Read", 25);
System.out.println(item.describe());
}
}
class ReportItem {
private final String title;
ReportItem(String title) {
if (title == null || title.trim().isEmpty()) {
throw new IllegalArgumentException("title required");
}
this.title = title.trim();
}
String title() {
return title;
}
String describe() {
return title;
}
}
final class TimedItem extends ReportItem {
private final int minutes;
TimedItem(String title, int minutes) {
super(title);
this.minutes = minutes;
}
@Override
String describe() {
return title() + ": " + minutes;
}
}Check your prediction
Read: 25Compare the behavior
Overloading is different from overriding. Two methods with the same name but different parameters are overloads. The compiler selects among them using the arguments' declared types. In this example Object is the declared type of value, even though its runtime object is a string. Do not expect overload resolution to act like an overridden instance method.
public class Main {
public static void main(String[] args) {
Object value = "Read";
System.out.println(label(value));
System.out.println(label("Read"));
}
static String label(Object value) {
return "object";
}
static String label(String value) {
return "string";
}
}Check your prediction
object
stringKeep substitution and reuse separate
A subclass is substitutable when callers can still rely on the parent contract. TimedItem can be used as a ReportItem because it keeps a valid title and supplies a meaningful description. The subclass can add data, but should not break a promise that an existing ReportItem caller depends on.
The parent constructor establishes the inherited part of the object. Calling super(title) does not create a separate unrelated ReportItem for the caller; it initializes parent state belonging to this TimedItem. The private title remains accessed through the parent's accessor.
Now contrast an override and an overload. An override has the same parameter signature and supplies behavior chosen by the runtime receiver. An overload has another parameter list and is selected using declared argument types at compile time. Keep @Override when replacing parent behavior so an accidental extra parameter becomes a diagnostic rather than a silent new method.
Practice independently
Inheritance & Overrides: practice
Create a Message parent with String text() returning "Hello", and an UrgentMessage subclass overriding it to return "Act now". Store each in a Message variable and print text(). Add @Override. Do not add a parameter just to make the compiler accept the method.
Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.
public class Main {
public static void main(String[] args) {
System.out.println("Write Message and UrgentMessage");
}
}Hint 1: the idea
The same signature creates an override; an extra parameter creates another method.
Hint 2: a first step
Copy the parent method signature into the subclass and annotate it with @Override.
Show one solution
One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?
public class Main {
public static void main(String[] args) {
Message ordinary = new Message();
Message urgent = new UrgentMessage();
System.out.println(ordinary.text());
System.out.println(urgent.text());
}
}
class Message {
String text() {
return "Hello";
}
}
final class UrgentMessage extends Message {
@Override
String text() {
return "Act now";
}
}Expected output:
Hello
Act nowChange it and test again
Change the child signature to text(int level) while leaving @Override. Read the compiler error. Remove the annotation and observe that text() now uses the inherited method. Restore the override. This is why a superficially similar method can be a silent behavior bug.
Explain before moving on
Why would making a task tracker extend ArrayList expose too much behavior? Describe a composition design that prevents callers from bypassing duplicate-ID checks.
Completion is saved in this browser only. It does not measure mastery.