链接构造函数的目的是什么



我是新手,有人可以帮我了解构造函数链接有用的场景类型以及程序中"this()"的目的是什么?这是代码。

public class Constructor_chaining {
Constructor_chaining(){
    System.out.println("Default constructor...");
}
Constructor_chaining(int i){
    this();
    System.out.println("Single parameterized constructor...");
}
Constructor_chaining(int i,int j){
    this(j);
    System.out.println("Double parameterized constructr...");
}
public static void main(String args[]){
    Constructor_chaining obj=new Constructor_chaining(10,20);
}}

它可用于避免代码重复。让我们举个例子:

public class Test
{
    int a;
    int b;
    public Test(int a)
    {
        this.a = a;
    }
    public Test(int a, int b)
    {
        this(a);
        this.b = b;
    }
    public static void main(String args[])
    {
        Test t1 = new Test(1);
        Test t2 = new Test(1,2);
        System.out.println(t1.a + " " + t1.b);
        System.out.println(t2.a + " " + t2.b);
    }
}

在这里,two-parameter constructor调用one-parameter constructor来初始化字段a,因此您不必在two-parameter constructor内重复one-parameter constructor中的所有代码。当然,有了这个小例子,它看起来没有用,但想象一下你有很多想要初始化的字段。这将非常有用。

关于this()问题:根据Java Docs:

在实例方法或构造函数中, this是对当前对象的引用...

在构造函数中,还可以使用 this 关键字调用同一类中的另一个构造函数。 这样做称为显式构造函数调用

所以this()用于调用类的构造函数(在本例中没有参数)Constructor_chaining

它的目的是减少代码重复。如果没有构造函数链接,您通常必须在另一个构造函数中重复一个构造函数中的任何内容。

典型情况下是默认参数的实现,其中一个构造函数 A 调用另一个 B 并为一个或多个参数提供固定值,同时直接传递其他参数。

最新更新