JavaSE系列代码12: 静态变量的使用

In the field of computer programming, static variable refers to a kind of variable for which the system allocates storage space statically (that is, the allocation will not be changed in the runtime) before the program is executed. Corresponding to it are the automatic variables (i.e. local variables) that only exist temporarily at runtime and some objects that obtain the storage space by dynamic allocation, in which the storage space of the automatic variables is allocated and released on the call stack.

class Cylinder     //定义类Cylinder
{
  private static int num=0;      //声明num为静态变量
  private static double pi=3.14;  //声明pi为静态变量,并赋初值
  private double radius;
  private int height;
  public Cylinder(double r, int h)  //定义有2个参数的构造方法
  {
    radius=r;
    height=h;
    num++;   //当构造方法Cylinder()被调用时,num便加1
  }
  public void count()     // count()方法用来显示目前创建对象的个数
  {
    System.out.print("创建了"+num+"个对象:");
  }
  double area()
  {
    return pi* radius* radius;
  }
  double volume()
  {
    return area()*height;
  }
}
public class Javase_12     //主类
{
  public static void main(String[] args)
  {
    Cylinder volu1=new Cylinder(2.5,5);
    volu1.count();
    System.out.println("圆柱1的体积="+volu1.volume());
    Cylinder volu2=new Cylinder(1.0,2);
    volu2.count();
    System.out.println("圆柱2的体积="+volu2.volume());
  }
}
发布了13 篇原创文章 · 获赞 160 · 访问量 8537

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105377316