Java Reference
In-Depth Information
Make sure that you have a good understanding of the four access modifi ers. We now
discuss the effect of the abstract modifi er on inheritance in Java.
The abstract Modifier
As you probably recall, we discussed the details of abstract methods and method overriding
in Chapter 2, “Declarations, Initialization, and Scoping.” The emphasis in this section is to
discuss the specifi c details of the abstract modifi er and its effect on inheritance. The abstract
modifi er declares a class or method as abstract and has the following effect on the class or
method:
An abstract class cannot be instantiated.
An abstract method must be overridden.
A class that contains an abstract method must also be declared abstract .
A child class must override the abstract methods in its parent class or the child class
must also be declared abstract .
The access modifier in the child class must be at least as accessible as the access
modifier of the abstract parent method.
For example, the following Shape class contains an abstract method named
computeArea :
public abstract class Shape {
private String color;
public Shape(String color) {
this.color = color;
}
protected abstract double computeArea();
}
Any non-abstract child class of Shape must declare a protected or public computeArea
method. For example, the following class does not compile:
public class InvalidShape extends Shape {
public InvalidShape(String color) {
super(color);
}
double computeArea() {
System.out.println(“Computing area...”);
return 0.0;
}
}
Search WWH ::




Custom Search