通过继承和重载的结合,超类可以定义供他所有子类可以使用方法的通用形式。如下代码:
class Figure
{
double dim1;
double dim2;
Figure(double a, double b)
{
dim1 = a;
dim2 = b;
}
double GetArea()
{
System.out.println("The figure is undefined!");
return 0;
}
}
class Rectangle extends Figure
{
Rectangle(double a, double b)
{
super(a, b);
}
double GetArea()
{
System.out.println("this is in Rectangle.");
return dim1 * dim2;
}
}
class Triangle extends Figure
{
Triangle(double a, double b)
{
super(a, b);
}
double GetArea()
{
System.out.println("this is in Triangle.");
return dim1 * dim2/2;
}
}
public class HelloWorld
{
public static void main(String[] args)
{
Figure f = new Figure(1, 2);
Rectangle r = new Rectangle(3, 4);
Triangle t = new Triangle(5, 6);
Figure area;
area = f;
System.out.println("area = " + area.GetArea());
area = r;
System.out.println("area = " + area.GetArea());
area = t;
System.out.println("area = " + area.GetArea());
}
}
运行结果:
The figure is undefined!
area = 0.0
this is in Rectangle.
area = 12.0
this is in Triangle.
area = 15.0