应用:getter和setter方法,继承extends
父类:几何图形(自写)
public class GeometricObject {
public double area;
public double diameter;
public double perimeter;
public double getArea() {
return area;
}
public double getDiameter() {
return diameter;
}
public double getPerimeter() {
return perimeter;
}
}
子类:圆
public class Circle extends GeometricObject{
private double radius;
public Circle() {
}
public Circle(double radius) {
this.radius=radius;
}
//系统自动写setter和getter方法
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
//重写父类方法
public double getArea() {
return radius*radius*Math.PI;
}
public double getDiameter() {
return 2*radius;
}
public double getPrimeter() {
return 2*radius*Math.PI;
}
public void printCircle() {
System.out.println("The circle is created "+ radius );
}
}
测试类
public class TestCircle {
public static void main(String[] args) {
Circle c = new Circle(5.0);
System.out.println("The circle's radius is "+c.getRadius());
System.out.println("The circle's area is "+c.getArea());
c.setRadius(c.getRadius()*1.1);
System.out.println("The circle's radius is "+c.getRadius());
System.out.println("The circle's area is "+c.getArea());
}
}