JavaSE系列代码11:公共构造方法与私有构造方法

Construction code block:
(1) Function: initializes the object, executes the object as soon as it is created, and takes precedence over the constructor
(2) Differences between building code blocks and constructors:
The construction code block is to initialize the commonness of all different objects, and the constructor is to initialize the corresponding objects

class Cylinder     //定义类Cylinder
{
  private double radius;
  private int height; 
  private double pi=3.14;
  String color;
  private Cylinder()  //定义私有的构造方法
  {
    System.out.println("无参构造方法被调用了");
  }
  public Cylinder(double r, int h, String str)  //定义有三个参数的构造方法
  {
    this();    //在公共构造方法中用this关键字来调用另一构造方法
    radius=r;
    height=h;
    color=str;
  }
  public void show()
  {
    System.out.println("圆柱底半径为:"+ radius);
    System.out.println("圆柱体的高为:"+ height);
    System.out.println("圆柱的颜色为:"+color);
  }
  double area()
  {
    return pi* radius* radius;
  }
  double volume()
  {
    return area()*height;
  }
}
public class Javase_11      //主类
{
  public static void main(String[] args)
  {
    Cylinder volu=new Cylinder(2.5,5,"蓝色");
    System.out.println("圆柱底面积="+ volu.area());
    System.out.println("圆柱体体积="+volu.volume());
    volu.show();
  }
}
发布了13 篇原创文章 · 获赞 160 · 访问量 8538

猜你喜欢

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