Java构造函数链接

jim*_*123 3 java constructor-chaining

嗨,我刚学习Java中的构造函数链接,并有一些问题......

  1. 首先,有人可以解释我何时需要使用它?在我的头脑中,我真的想不到一个情况.

  2. 在这个例子中,在没有参数的构造函数中,我调用另一个构造函数.如何访问这个新的"James Bond"对象以备将来使用?

    import java.util.*;
    
    class Employee
    {   
        private String name;
        private double salary;
    
        public Employee()
        {
            this("James Bond", 34000);
        }
    
        public Employee(String n, double s)
        {
            name = n;
            salary = s;
        }
    
        public String getName()
        {
            return name;
        }
    
        public double getSalary()
        {
            return salary;
        }
    
        public static void main(String[] args)
        {
            Employee a = new Employee();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

Adr*_*ndl 5

实际上我相信链式构造函数最常见的用法是构造函数不仅仅是设置成员变量.

static int numOfExamples = 0;
public Example(String name, int num)
{
    this.name = name;
    this.num = num;
    numOfExamples++;
    System.out.println("Constructor called.");
    Log.info("Constructor called");
}

public Example()
{
    this("James Bond",3);
}
Run Code Online (Sandbox Code Playgroud)

这样我们就不必编写用于记录和增加静态变量两次的代码,而只需链接构造函数.