Java Reference
In-Depth Information
I like to use an example about mammals when discussing abstraction. If I
asked you to draw me a picture of a mammal, you would likely draw a dog,
horse, person, or something similar. If I asked you to draw a picture of some-
thing that was just a mammal, you can see how the concept of a mammal is
abstract. Many animals are mammals, but no animal is just a mammal. It
seems logical, therefore, that no one would need to instantiate an object of type
Mammal (assuming that we wrote a Mammal class). Similarly, all of our
employees in our company are of type Employee, but no one is just an
Employee. It seems logical that no one would need to instantiate an object of
type Employee, and it should be declared abstract.
Let's now look at how to declare a class abstract in Java.
Abstract Classes
Use the abstract keyword to declare a class abstract. The keyword appears in
the class declaration somewhere before the class keyword. For example, the
Employee class in Listing 8.13 is declared as abstract.
public abstract class Employee
{
private String name;
private String address;
private int number;
public Employee(String name, String address, int number)
{
System.out.println(“Constructing an Employee”);
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println(“Inside Employee computePay”);
return 0.0;
}
public void mailCheck()
{
System.out.println(“Mailing a check to “
+ this.name + “ “ + this.address);
}
public String toString()
Listing 8.13
The Employee class is declared abstract by using the abstract keyword.
Search WWH ::




Custom Search