JavaSE系列代码10:从某一构造方法调用另一构造方法

The construction method is a special member method, and its particularity is reflected in the following aspects:

  1. Constructor function: (1) construct an instance of a class (2). Initialize the instance (object) of a class.
  2. The name of the constructor must be exactly the same as the class name that defines it. There is no return type or even void.
  3. The main task is to initialize the object. The call of construction method is to use the new operation when creating an object.
  4. There must be a constructor in the class. If it is not written, the system will automatically add a nonparametric constructor. The interface is not allowed to be instantiated, so there is no constructor in the interface.
  5. Cannot be modified by static, final, synchronized, abstract and native.
  6. Construction methods are automatically executed when initializing objects, and cannot be called explicitly directly. When there are multiple construction methods in the same class, the Java compilation system will automatically correspond one-to-one according to the number of parameters and parameter types in the last bracket during initialization. Complete the call to the constructor.
  7. There are two construction methods: nonparametric construction method and parametric construction method
class Cylinder       //定义类Cylinder
{
  private double radius;
  private int height; 
  private double pi=3.14;
  String color;
  public Cylinder()  //定义无参数的构造方法
  {
    this(2.5, 5, "红色");    //用this关键字来调用另一构造方法
    System.out.println("无参构造方法被调用了");
  }
  public Cylinder(double r, int h, String str)  //定义有三个参数的构造方法
  {
    System.out.println("有参构造方法被调用了");
    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_10      //主类
{
  public static void main(String[] args)
  {
    Cylinder volu=new Cylinder();
    System.out.println("圆柱底面积="+ volu.area());
    System.out.println("圆柱体体积="+volu.volume());
    volu.show();
  }
}
发布了13 篇原创文章 · 获赞 160 · 访问量 8539

猜你喜欢

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