JavaSE系列代码09:构造方法的使用

Construction method is a special method, which has the same name as the class. The creation of objects is accomplished by constructing methods, whose function is mainly to complete the initialization of objects. The constructor is called automatically when the class instantiates an object. Construction methods can be overloaded as well as other methods.

class Cylinder     //定义类Cylinder
{
  private double radius;
  private int height; 
  private double pi=3.14;
  public Cylinder(double r, int h)    //定义构造方法
  {
    radius=r;
    height=h;
  }
  double area()
  {
    return pi* radius* radius;
  }
  double volume()
  {
    return area()*height;
  }
}
public class Javase_09       //定义主类
{
  public static void main(String[] args)
  {
    Cylinder volu=new Cylinder(3.5, 8);   //创建对象并调用构造方法
    System.out.println("圆柱底积="+ volu.area());
    System.out.println("圆柱体体积="+volu.volume());
  }
}
发布了13 篇原创文章 · 获赞 160 · 访问量 8540

猜你喜欢

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