Java:为什么缺少" new"实例化对象时的运算符?

时间:2015-02-03 23:04:22

标签: java android

以下是JavaDeveloper网站上的演示代码方法。

我有一个快速而简单的问题:在第三行,代码是......

final ViewGroup newView = (ViewGroup)LayoutInflater.from(this).inflate(R.layout.list_item_example, mContainerView, false);

有人告诉我,在实例化一个对象时,应该有一个“new”运算符。为什么“newView”没有“新”运算符?当我尝试在“=”符号后添加“新”时,Android Studio显示“不是声明”错误。

private void addItem() {
    // Instantiate a new "row" view.
    final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(
            R.layout.list_item_example, mContainerView, false);

    // Set the text in the new row to a random country.
    ((TextView) newView.findViewById(android.R.id.text1)).setText(
            COUNTRIES[(int) (Math.random() * COUNTRIES.length)]);

    // Set a click listener for the "X" button in the row that will remove the row.
    newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Remove the row from its parent (the container view).
            // Because mContainerView has android:animateLayoutChanges set to true,
            // this removal is automatically animated.
            mContainerView.removeView(newView);

            // If there are no rows remaining, show the empty view.
            if (mContainerView.getChildCount() == 0) {
                findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
            }
        }
    });

    // Because mContainerView has android:animateLayoutChanges set to true,
    // adding this view is automatically animated.
    mContainerView.addView(newView, 0);
}

2 个答案:

答案 0 :(得分:6)

您正在调用一种方法,该方法在其实现的某个地方已经使用new。这被称为工厂方法,它在Java中是一种非常普遍的实践 - 这是有充分理由的。

例如,请考虑以下方法:

Foo createFoo() {
  return new Foo();
}

...您可以在不自己编写createFoo()的情况下调用new,并在其实现中生成新对象。这就是这里发生的事情。

答案 1 :(得分:5)

因为Inflater本身正在创建对象 - 它返回new View()。任何时候从一个函数返回一个对象,它必须已经被实例化,所以不需要new。