package 圆的周长;//圆类
public class Circle
{
private double radius;//一个成员变量 Radius(私有,浮点型); 存放圆的半径;
public void setRadius(double R) //设置半径,方便传参
{
radius = R;
}
public double getradius()//方便显示半径
{
return radius;
}
public static double PI=3.14;//定义静态变量,可全局使用
//public Circle()// 将半径设为0
//{ System.out.println("圆"); }
public Circle(double r)//构造函数,创建Circle对象时将半径初始化为r
{ radius=r; }
public double getArea()//获取圆的面积
{
return PI*radius*radius;
}
public double getPerimeter()//获取圆的周长
{
return PI*2*radius;
}
public void show()//将圆的半径、周长、面积输出到屏幕
{
System.out.println("圆的半径:"+getradius()+"m");
System.out.println("圆的面积:"+getArea()+"m2");
System.out.println("圆的周长:"+getPerimeter()+"m");
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------
package 圆的周长;//圆柱类
public class Circular extends Circle {
private double hight;
public Circular (double r, double h )//构造函数,由主函数调用时传参
{
super(r);//子类引用父类成员
hight=h;
}
public double getVolume()
{
return getArea() * hight;//体积=底面积×高
//return PI * THIS.radius* radius * hight;因radius是私有的不能被此类调用,除非改为公有
}
public void showVolume( )//显示圆柱体积
{
System.out.println("圆柱体的体积:" + getVolume()+"m3");
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
package 圆的周长;//主函数类
import java.util.Scanner;//输入头文件
public class MAIN {
public static void main(String[] args)//注意String是大写S
{
double R,H;
Scanner s=new Scanner(System.in);
System.out.println("请输入圆的半径:"+"m");
R=s.nextInt();
Circle c1=new Circle(R);//定义对象圆c1,并调用构造函数初始化半径
c1.show( );
System.out.println("请输入圆柱的高:"+"m");
Scanner n=new Scanner(System.in);
H=n.nextInt();
Circular C11=new Circular (R, H);//定义对象圆柱体C11,并调用构造函数初始化半径和高
C11.showVolume();
}
}
-------------------------------------------------------------------------------------------------------------------------------
结果:
请输入圆的半径:m
2
圆的半径:2.0m
圆的面积:12.56m2
圆的周长:12.56m
请输入圆柱的高:m
5
圆柱体的体积:62.800000000000004m3