Java Reference
In-Depth Information
// Provide an implementation for inherited abstract getArea() method
public double getArea() {
return width * height;
}
// Provide an implementation for inherited abstract getPerimeter() method
public double getPerimeter() {
return 2.0 * (width + height);
}
}
Note that you have not declared the Rectangle class abstract , which means that it is a concrete class and
its objects can be created. An abstract method is also inherited by a subclass like any other methods. Since the
Rectangle class is not declared abstract , it must override all three abstract methods of its superclass and provide
implementations for them. If the Rectangle class does not override all abstract methods of its superclass and
provides implementation for them, it is considered incomplete and must be declared abstract . Your Rectangle class
overrides the draw() , getArea() , and getPerimeter() methods of the Shape class and provides implementation
(body within braces) for them. The instance variables width and height are used to keep track of width and
height of the rectangle. Inside the constructor, you call the constructor of the Shape class using super keyword,
super("Rectangle") , to set its name. Listing 16-38 has code for a Circle class, which inherits from the Shape class.
It also overrides three abstract methods of the Shape class and provides implementations for them.
Listing 16-38. A Circle Class, Which Inherits from Shape Class
// Circle.java
package com.jdojo.inheritance;
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
super("Circle");
this.radius = radius;
}
// Provide an implementation for inherited abstract draw() method
public void draw() {
System.out.println("Drawing a circle...");
}
// Provide an implementation for inherited abstract getArea() method
public double getArea() {
return Math.PI * radius * radius;
}
// Provide an implementation for inherited abstract getPerimeter() method
public double getPerimeter() {
return 2.0 * Math.PI * radius;
}
}
 
Search WWH ::




Custom Search