引用构造函数中的方法 (java)

Refer to method in a constructor (java)

class A {

    private List<B> list = new ArrayList<B>();
    private B example;

    public A(List<B> list) {
        this.list = list; 
        this.example = setExample();
    }

    private B setExample() {
        B object;
        //do something with the list
        return object;
    }

}

这样的事情可能吗?该对象有一个列表,但我希望该列表的特定元素也存储在该对象中。

是的,只要该方法不可覆盖就可以。不得在构造函数中调用可覆盖的方法。

因此,如果这个 class 被设计为继承,setExample() 方法应该是最终的,如果它是 public 或受保护但它是私有的,所以这不是问题。

是的,这工作正常,但您不需要用空列表初始化变量 list,因为您在构造函数中将传递的列表分配给它,有效地再次丢弃新列表。