Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/gwt/3.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
如何在get方法中创建新字符串?(Java)_Java - Fatal编程技术网

如何在get方法中创建新字符串?(Java)

如何在get方法中创建新字符串?(Java),java,Java,我有下面的代码。如果行中没有其他人,我希望我的getMother方法创建一个新字符串或名为“Eva”的人并返回这个字符串。 我的代码不起作用。我总是得到“空”。我该怎么做?请帮忙 public Person getMother() { if (mother == null) { Person p = new Person("Eva"); } return mother; } 您应该初始化mother,而不是p: public Pers

我有下面的代码。如果行中没有其他人,我希望我的getMother方法创建一个新字符串或名为“Eva”的人并返回这个字符串。 我的代码不起作用。我总是得到“空”。我该怎么做?请帮忙

public Person getMother() {
     if (mother == null) {
       Person p = new Person("Eva");
       }
       return mother;

   }

您应该初始化
mother
,而不是
p

public Person getMother() {
    if (mother == null) {
        mother = new Person("Eva");
    }
    return mother;
}

你的标题、问题和代码都有不同的含义。我不知道你想问什么,但我认为@Adem的回答是正确的。你认为这段代码怎么能不为null????实际上,您正在返回相同的空值!再次检查你的代码,大声问它做什么和返回什么。thx我会在“冷却”结束后接受它