记录我的第一个csdn
在编写一个简单的方法Java调用程序的时候遇到的问题:
这里有圆类,圆柱类(圆柱类继承圆类)以及测试类,想通过圆柱类继承圆类里面的半径变量里面的值,从而输出圆柱的体积和其表面积。结果圆柱类的结果却始终为0,这困扰了我好久,终于在朋友和查阅资料的帮助下,解决了!
总结:
注重基础知识!!
下面是我的源码:
//圆类
package com.it3;
public class Three_Circle {
***static*** int r;//圆半径
public Three_Circle() {
}
public Three_Circle(int r) {
this.r = r;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
//获取圆的半径
public double getRadius() {
return this.r;
}
//获取圆的周长
public double getPerimeter() {
//System.out.println("圆的周长是:" + 2 * Math.PI * r);
double perimeter = 2 * Math.PI * r;
return perimeter;
}
//获取圆的面积
public double getArea() {
//System.out.println("圆的面积是:" + 2 * Math.PI * r * r);
double area = 2 * Math.PI * r * r;
return area;
}
public void disp() {
System.out.println("圆的半径是:" + r);
System.out.println("圆的周长是:" + getPerimeter());
System.out.println("圆的面积是:" + getArea());
}
}
圆类,目的输出圆的面积周长和半径
//圆柱类
package com.it3;
public class Three_Cylinder extends Three_Circle {
public int h;//圆柱体的高
public Three_Cylinder(int h) {
this.h = h;
}
public Three_Cylinder(int r, int h) {
super(r);
this.h = h;
}
//获取圆柱体的高
public double getHeight(int h) {
return h;
}
//获取圆柱体的表面积(侧面积+两个底面积)
public double getCylinderArea() {
double rr = getRadius();
double area1 = 2 * Math.PI * rr * h + 2 * Math.PI * rr * rr * 2;
return area1;
}
//获取圆柱体的体积(底面积*高)
public double getVol() {
double rr = getRadius();
double vol = 2 * Math.PI * rr * rr * h;
return vol;
}
public void dispVol() {
System.out.println("圆柱体的面积是:"+getCylinderArea());
System.out.println("圆柱体的体积是:" + getVol());
}
}
圆柱类,目的输出圆柱的体积和面积
package com.it3;
// 测试类
public class Test_Three {
public static void main(String[] args) {
Three_Circle tc = new Three_Circle(2);
// tc.getRadius(2);
tc.disp();
System.out.println("-----------");
Three_Cylinder tcl = new Three_Cylinder(3);
tcl.dispVol();
}
}
最终解决方法很容易:只需要把圆类里面的变量 r 用static修饰!!