Java,为Cylinder类添加一个无参的构造方法(设定radius变量值为3,height变量值为10)和一个有参的构造方法,并利用构造方法来初始化圆柱体类Cylinder的成员变量,分别用无参构造方法和有参构造方法创建对象Cylinder1和Cylinder2,并调用相应的方法求圆柱的底面积和体积。
请教一下各位有没有人会啊
public class Cylinder {
public double radius=3;
public double height=10;
public Cylinder(){
}
public Cylinder(double radius,double height){
this.radius=radius;
this.height=height;
}
public void print(){
System.out.println("底面积为"+3.14*radius*radius+"体积为"+3.14*radius*radius*height);
}
public static void main(String[] args) {
Cylinder cylinder1=new Cylinder();
cylinder1.print();
Cylinder cylinder2=new Cylinder(1,1);
cylinder2.print();
}
}
这应该比较简单的,示例如下:
public Class Cylinder{
private Integer radius;
private Integer height;
//相应的set和get,忽略
public Cylinder(){
this.radius = 3;
this.height = 10;
}
public Cylinder(Integer radius,Integer height){
this.radius = radius;
this.height = height;
}
public Double getArea(){
return this.radius * this.radius * 3.14;
}
public Double getTiJi(){
return this.getArea() * this.heigth;
}
public static void main(String[] args) {
Cylinder c1 = new Cylinder();
c1.getArea();
c1.getTiji();
Cylinder c2 = new Cylinder (5,8);
c2.getArea();
c2.getTiji();
}
}
完全手敲,大概意思应该是这样的,希望可以帮到你。