简体   繁体   English

从另一个构造函数调用构造函数的真实场景

[英]Real life scenarios for calling a constructor from another constructor

I know it is possible to call one constructor from another constructor via the use of "this". 我知道可以通过使用“this”从另一个构造函数调用一个构造函数。

But I would like to know is, why do we do it (ie calling a constructor from another constructor) 但我想知道的是,为什么我们这样做(即从另一个构造函数调用构造函数)

Can anyone relate a simple example of where this might be actually useful ? 任何人都可以提到一个简单的例子,说明这可能实际上有用吗?

ArrayList is a nice example. ArrayList是一个很好的例子。 The default constructor calls the constructor that takes the initial capacity of the underlying array. 默认构造函数调用获取底层数组初始容量的构造函数。 This looks like this: 这看起来像这样:

public ArrayList()
{
    this(10);
}

public ArrayList(int capacity)
{
    objects = new Object[capacity];
}

If we do not want to duplicate code: 如果我们不想重复代码:

class Foo{

    int requiredParam;
    String name;
    double optionalPrice;
    Object extraObject;
    public Foo(int rp, String name){
        this.requiredParam=rp;
        this.name=name
    }
    public Foo(int rp, String name, double op, Object e){
        this(rp, name);
        this.optionalPrice=op;
        this.extraObject=e;
    }

How about a simple class like this: 这样一个简单的类怎么样:

  class Person {

        String name;

        Person(String firstName, String lastName) {
            this(firstName + lastName);
        }

        Person(String fullName) {
            name = fullName;
        }
    }

Different constructors give you the freedom of creating similar objects in different flavors. 不同的构造函数使您可以自由地创建不同风格的类似对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM