Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/380.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java:为什么在实例化对象时缺少“new”操作符?_Java_Android - Fatal编程技术网

Java:为什么在实例化对象时缺少“new”操作符?

Java:为什么在实例化对象时缺少“new”操作符?,java,android,Java,Android,下面是JavaDeveloper网站上演示代码的方法 我有一个简单的问题:在第三行,代码是 final ViewGroup newView = (ViewGroup)LayoutInflater.from(this).inflate(R.layout.list_item_example, mContainerView, false); 有人告诉我们,当实例化一个对象时,应该有一个新的操作符。为什么newView没有新的操作符?当我尝试添加一个新的after=符号时,Android Studio

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

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

final ViewGroup newView = (ViewGroup)LayoutInflater.from(this).inflate(R.layout.list_item_example, mContainerView, false);
有人告诉我们,当实例化一个对象时,应该有一个新的操作符。为什么newView没有新的操作符?当我尝试添加一个新的after=符号时,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);
}

因为充气机本身正在创建对象-它将返回一个新视图。任何时候,从函数返回的对象必须已经实例化,因此不需要new。

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

例如,考虑以下方法:

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

…您可以直接调用createFoo,而无需自己编写新的,在其实现中,它将生成新对象。这就是这里发生的事情。

看看布洛赫的高效Java。他在书的开头解释了开发人员如何创建对象。这是一个非常有用的答案@盖布·塞尚