Java Reference
In-Depth Information
In the following standard example, we create a base class Shape ,which
provides a method that calculates the area of some 2D shape:
public class Shape {
double getArea () {
return 0.0;
}
}
The Shape class itself does almost nothing. To be useful, there must be subclasses
of Shape defined for each desired 2D shape, and each subclass should override
getArea() to perform the proper area calculation for that particular shape. We
illustrate with two shapes-arectangle and a circle.
public class Rectangle extends Shape {
double ht = 0.0;
double wd = 0.0;
public double getArea () {
return ht*wd;
}
public void setHeight (double ht) {
this.ht = ht;
}
public void setWidth (double wd) {
this.wd = wd;
}
}
public class Circle extends Shape {
double r =0.0;
public double getArea () {
return Math.PI*r*r;
}
public void setRadius (double r) {
this.r = r;
}
}
The subclasses Rectangle and Circle extend Shape and each overrides the
getArea() method. We could define similar subclasses for other shapes as well.
Each shape subclass requires a unique area calculation and returns a double
value. The default area calculation in the base class does essentially nothing but
it must be declared to return a double for the benefit of the subclass methods
that do return values. Since its signature requires that it return something, it was
 
Search WWH ::




Custom Search