无法在Java中使用组合引用方法

huangapple go评论125阅读模式
英文:

Not able to refer a method using composition in java

问题

为什么这样是允许的

```java
import java.util.ArrayList;

public class BurgerClass {

	private DefaultMenuClass defaultMenu;
	ArrayList<String> burgerMenuItems = new ArrayList<String>();
	
	public void displayBurgerMenu() {
		
		burgerMenuItems = defaultMenu.getDefaultBurgerMenu();
		for (String burger : burgerMenuItems) {
			System.out.println(burger + "\n");
		}

	}
}

而这样不行:

import java.util.ArrayList;

public class BurgerClass {

	private DefaultMenuClass defaultMenu;
	ArrayList<String> burgerMenuItems = new ArrayList<String>();
	burgerMenuItems = defaultMenu.getDefaultBurgerMenu(); // 在这里有错误
	public void displayBurgerMenu() {
		
		
		for (String burger : burgerMenuItems) {
			System.out.println(burger + "\n");
		}

	}
}
英文:

Why is this allowed:

import java.util.ArrayList;

public class BurgerClass {

	private DefaultMenuClass defaultMenu;
	ArrayList&lt;String&gt; burgerMenuItems = new ArrayList&lt;String&gt;();
	
	public void displayBurgerMenu() {
		
		burgerMenuItems = defaultMenu.getDefaultBurgerMenu();
		for (String burger : burgerMenuItems) {
			System.out.println(burger + &quot;\n&quot;);
		}

	}
}

And this isn't:

import java.util.ArrayList;

public class BurgerClass {

	private DefaultMenuClass defaultMenu;
	ArrayList&lt;String&gt; burgerMenuItems = new ArrayList&lt;String&gt;();
	burgerMenuItems = defaultMenu.getDefaultBurgerMenu(); //error here
	public void displayBurgerMenu() {
		
		
		for (String burger : burgerMenuItems) {
			System.out.println(burger + &quot;\n&quot;);
		}

	}
}

答案1

得分: 2

为了回答具体的问题,第一个被“允许”的原因和第二个不被允许的原因是:

两者都不被“允许”或“不允许”。

在两种情况下,正如Mureinik所说,“defaultMenu”都没有被初始化。在第一种情况下,这并不重要,因为“displayBurgerMenu()”从未被调用,所以永远不会到达行“burgerMenuItems = defaultMenu.getDefaultBurgerMenu();”,这会引发错误。

在第二种情况下,您确实尝试调用它,在您标记的行“//error here”处,所以您会得到(我假设*)一个NullPointerException。

无论哪种方式,您都需要在尝试调用其上的方法之前初始化“defaultMenu”为非null的值。

您需要做一些类似于

private DefaultMenuClass defaultMenu = new DefaultMenuClass(<some-params>);

或者以某种方式获取“DefaultMenuClass”对象。仅根据您在问题中提供的代码,无法确定应该如何完成这个操作。

另外,与您的错误无关,同时执行

ArrayList<String> burgerMenuItems = new ArrayList<String>();

然后

burgerMenuItems = defaultMenu.getDefaultBurgerMenu();

是没有意义的。

您将“burgerMenuItems”初始化为空的“ArrayList”,然后立即通过将其设置为“.getDefaultBurgerMenu()”返回的列表(如果没有错误并且返回了某些内容)而抛弃该列表。

  • 您应该在问题中明确说明您得到了什么错误,而不要让我们去猜测。
英文:

To answer the specific question, the reason why the first is "allowed" and the second isn't ——

Neither one is "allowed" or "disallowed"

In both cases, as Mureinik says, defaultMenu is never initialized. In the first case it doesn't matter, because displayBurgerMenu() is never called, so you never reach the line burgerMenuItems = defaultMenu.getDefaultBurgerMenu(); which would cause an error.

In the second case you do attempt to call it, at the line you've marked //error here so you get (I assume<sup>*</sup>) a NullPointerException.

Either way, you need to initialize defaultMenu to be something that is non-null before you attempt to call a method on it.

You need to do something along the lines of
private DefaultMenuClass defaultMenu = new DefaultMenuClass(&lt;some-params?&gt;);

or have some other way to get a DefaultMenuClass object. It's impossible to tell how that should happen given only the code you've presented in the question.


Separately, and not having anything to do with your error, it's pointless to do both
ArrayList&lt;String&gt; burgerMenuItems = new ArrayList&lt;String&gt;();
and then
burgerMenuItems = defaultMenu.getDefaultBurgerMenu();

You initialize burgerMenuItems to an empty ArrayList then you immediately throw that list away by setting burgerMenuItems to the list returned by .getDefaultBurgerMenu() (if there had been no error and something was returned)


* You really should say what error you are getting in your question, and not leave us to assume something.

答案2

得分: 0

@Data
@Builder
class BurgerClass {
    private DefaultMenuClass defaultMenu;

    public void displayBurgerMenu() {
        List<String> burgerMenuItems = defaultMenu.getDefaultBurgerMenu();
        for (String burger : burgerMenuItems) {
            System.out.println(burger + "\n");
        }
    }
}

@Data
@Builder
class DefaultMenuClass {
    List<String> defaultBurgerMenu;

    public DefaultMenuClass(List<String> defaultBurgerMenu) {
        this.defaultBurgerMenu = defaultBurgerMenu;
    }
}

class Main {
    public static void main(String[] args) {
        BurgerClass obj = BurgerClass.builder()
                .defaultMenu(DefaultMenuClass.builder()
                        .defaultBurgerMenu(Arrays.asList(new String[]{"Item1", "Item2"}))
                        .build())
                .build();
        obj.displayBurgerMenu();
    }
}

And while creating an instance of BurgerClass, pass the value of DefaultMenuClass:

public BurgerClass(DefaultMenuClass defaultMenu) {
    this.defaultMenu = defaultMenu;
}

Just run the above code, and you will get an idea.

英文:
@Data
@Builder
class BurgerClass {
    private DefaultMenuClass defaultMenu;

    public void displayBurgerMenu() {
        List&lt;String&gt; burgerMenuItems = defaultMenu.getDefaultBurgerMenu();
        for (String burger : burgerMenuItems) {
            System.out.println(burger + &quot;\n&quot;);
        }
    }
}

@Data
@Builder
class DefaultMenuClass {
    List&lt;String&gt; defaultBurgerMenu;

    public DefaultMenuClass(List&lt;String&gt; defaultBurgerMenu) {
        this.defaultBurgerMenu = defaultBurgerMenu;
    }
}

class Main {
    public static void main(String[] args) {
        BurgerClass obj = BurgerClass.builder().defaultMenu(DefaultMenuClass.builder().defaultBurgerMenu(Arrays.asList(new String[]{&quot;Item1&quot;, &quot;Item2&quot;})).build()).build();
        obj.displayBurgerMenu();
    }
}

As you can able to see in above code,i am initialize all attribute of BurgerClass by providing builder pattern.

Also you can initialize dafaultMenu attributes using constructor. And while creating an instance of BurgerClass pass value of DefaultMenuClass.

 public BurgerClass(DefaultMenuClass defaultMenu) {
        this.defaultMenu = defaultMenu;
    }

Just run above code, you will get an idea.

huangapple
  • 本文由 发表于 2020年8月24日 04:22:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63551648.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定