必须使用extend来定义子类(子类可以调用父类)
例:主方法中用Cylinder创建的对象cylin可以调不属于Cylinder类中的方法SetRadius(),因为SetRadius()是Cylinder父类中的方法。
class Circle{ //定义圆类
double radius;
public void setRadius(double r){
radius = r;
}
public double getRadius(){
return radius;
}
public double perimeter(){
return 2*Math.PI*radius;
}
public double area(){
return Math.PI*radius*radius;
}
}
class Cylinder extends Circle{//Circle的子类
private double height;
public void setHeight(double h){
height = h;
}
public double getHeight(){
return height;
}
public double volume(){
return area() * height;
}
}
public class CylinderTest{
public static void main(String[] args){
Cylinder cylin = new Cylinder();
cylin.setRadius(10);
cylin.setHeight(20);
System.out.printf("The perimeter=%8.2f%n", cylin.perimeter());
System.out.printf("The floor area=%8.2f%n", cylin.area());
System.out.printf("The volume =%8.2f", cylin.volume());
}
}