public Sphere(){//构造方法:无参数
this.diameter = 1.0;
}
public Sphere(double d){ //构造方法:带一个参数
this.diameter = d;
}
public void setDiameter(double d) {//设置直径值的方法 this.diameter = d;
}
public double getDiameter(){//获取直径值的方法
return this.diameter;
}
public double volume(){//计算球的体积
return 4*Math.PI*Math.pow(this.diameter/2,3)/3; }
public double area(){//计算球的表面积
return 4*Math.PI*Math.pow(this.diameter/2,2);
}
public String toString(){
String out = "该球体的直径为:" + this.diameter + "\n" + "该球体的表面积为:" + this.area() + "\n" +
"该球体的体积为:" + this. volume();
return out;
}
}
//MultiSphere.java
import java.util.Scanner;
public class MultiSphere
{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
Sphere sphere1 = new Sphere();
Sphere sphere2 = new Sphere(3.5);
System.out.println("sphere1: " + sphere1 + "\n"); System.out.println("sphere2: " + sphere2 + "\n");
System.out.println("sphere1和sphere2分别调用无参构造方法" +
"和带一个参数的构造方法进行初始化。");
System.out.print("现在,请输入一个数作为球sphere1的直径值:");
sphere1.setDiameter(scan.nextDouble());
System.out.println("\n" + "更改过的sphere1: " + sphere1);
}