定义Circle类并使用该类创建对象。构造三个圆对象,其半径分别为1,25和125,然后显示这三个圆的半径和面积。接着将第二个对象的半径改为100,并显示新的半径和面积。
public class TestCircle {
public static void main(String[] args) {
Circle circle1 = new Circle(1);
System.out.println("The area of the circle of radius " + circle1.radius + " is " +
circle1.getArea());
Circle circle2 = new Circle(25);
System.out.println("The area of the circle of radius " + circle2.radius + " is " +
circle2.getArea());
Circle circle3 = new Circle(125);
System.out.println("The area of the circle of radius " + circle3.radius + " is " +
circle3.getArea());
circle2.radius = 100;
System.out.println("The area of the circle of radius " + circle2.radius + " is " +
circle2.getArea());
}
}
class Circle {
double radius;
Circle() {
}
Circle(double radius) {
this.radius = radius;
}
double getArea() {
return radius*radius*Math.PI;
}
double getPerimeter() {
return 2*radius*Math.PI;
}
void setRadius(double radius) {
this.radius = radius;
}
}
1.使用new操作符从构造方法创建一个对象:new Circle(1)创建一个半径为1的对象(第3行)
创建对象:类名 对象名 = new 类名()
2.getArea()方法计算它们各自的面积
3.使用circle1.radius通过对象引用来访问数据域
4.使用circle1.getArea()通过引用来调用方法



