Abstract classes
SinceContact
is a class, not an interface, it would be possible to construct one:
Contact c = new Contact("Ewan", "Zimblekiss"); c.notify("Giraffe!");But this doesn't make any sense. The
notify
method can't possibly do anything sensible, because the general Contact
type doesn't know how to contact anyone. Would it make more sense for Contact
to be an interface?
Well, sort of - we want to specify the notify
method only, and leave it up to the subclasses to choose how to implement it. On the other hand, there are some parts of the implementation, like storing the first and last name, that are the same for all possible subclasses.
We want something that lets us specify the notify
method without an implementation, yet allows us to provide some other aspects of the implementation to be inherited by all subclasses. What we want is called an abstract class.
public abstract class Contact { private String firstName; private String lastName; public Contact(String givenFirstName, String givenLastName) { firstName = givenFirstName; lastName = givenLastName; } public String getName() { return firstName + " " + lastName; } public abstract notify(String alertMessage); }By declaring the
notify
method to be abstract, we don't have to provide a method body. This requires us to declare the whole class to be abstract as well. This means that, like an interface, you can't directly create one using the new
operator.
In an interface, all the methods are automatically abstract, so you don't need to use the abstract
keyword. A class that is not abstract is called concrete.