Java Reference
In-Depth Information
public Shape(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
// Abstract methods
public abstract void draw();
public abstract double getArea();
public abstract double getPerimeter();
}
Each shape will have a name. The name instance variable stores the name of the shape. The getName() and
setName() methods let you read and change the name of the shape, respectively. Two constructors let you set the
name of the shape or leave the name as the default name “Unknown shape”. A shape does not know how to draw, so
it has declared its draw() method abstract . A shape also does not know how to compute its area and perimeter, so it
has declared getArea() and getPerimeter() methods abstract .
An abstract class guarantees the use of inheritance, at least theoretically. Otherwise, an abstract class by itself
is useless. For example, until someone supplies the implementations for the abstract methods of the Shape class,
its other parts (instance variables, concrete methods, and constructors) are of no use. You create subclasses of an
abstract class, which override the abstract methods providing implementations for them.
Listing 16-37 has code for a Rectangle class, which inherits from the Shape class.
Listing 16-37. A Rectangle Class, Which Inherits from the Shape Class
// Rectangle.java
package com.jdojo.inheritance;
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
// Set the shape name as "Rectangle"
super("Rectangle");
this.width = width;
this.height = height;
}
// Provide an implementation for inherited abstract draw() method
public void draw() {
System.out.println("Drawing a rectangle...");
}
 
Search WWH ::




Custom Search