Video in progress
If you can't create an object from an abstract class, why does it need a constructor?
An abstract class has its own fields too, and the constructor is needed to fill them and check invariants. When a child class is created, the constructor is always called through super(...), so the shared initialization code lives in one place.
📖 Answer
public abstract class Notification {
private final String recipient;
private final Instant createdAt;
protected Notification(String recipient) {
if (recipient == null || recipient.isBlank())
throw new IllegalArgumentException("Qabul qiluvchi bo'sh");
this.recipient = recipient;
this.createdAt = Instant.now();
}
public abstract void send();
protected String recipient() { return recipient; }
}
public class SmsNotification extends Notification {
private final String text;
public SmsNotification(String phone, String text) {
super(phone); // the shared validation and initialization
this.text = text;
}
@Override public void send() { /* ... */ }
}
Without the constructor, every child class would have to repeat the recipient check itself, and one of them would surely forget.
A few tips:
- make an abstract class constructor
protected; there is no point in making itpublic, since only children can call it anyway; - don't call abstract methods inside the constructor, because the child's fields aren't ready yet;
- assign the
finalfields here, so child classes can't change them.
Sign up to mark studied questions and save your progress.