繁体   English   中英

无法从外部main引用main中创建的对象

[英]Cannot reference an object created in main from outside main

我有一堂课,有很多人。 我做了一个类PersonBeholder(在挪威语中是PersonContainer的意思)。 我也有一个Person类,和一个建立人与人之间关系的主要类。 当我尝试从主要班级以外的人的总名单上查询时,我遇到了问题。

class TestPersoner{
public static void main (String [ ] args){

   **PersonBeholder pl = new PersonBeholder();**

    Person Emil = new Person("Emil");
    Person Nils = new Person("Nils");

    pl.settInnPerson(Emil);        //this populates the list
    pl.settInnPerson(Nils);

    }

}

现在,当我尝试从外部main引用PersonBeholder pl时遇到问题:

public void blirVennMed(Person p){
if(!pl.erIbeholder(p.hentNavn())) System.out.print("This is not going to work");
//this does check if there is someone in the container named p.hentNavn()
}

输出值

TestPersoner.java:26: error: cannot find symbol
if(!pl.erIbeholder(p.hentNavn())) System.out.print("This is not going to work");
    ^
  symbol:   variable pl
  location: class Person
1 error

现在,我这样做是这样的:

class TestPersoner{
public static PersonBeholder pl = new PersonBeholder();
public static void main (String [ ] args){  

    Person Emil = new Person("Emil");
    Person Nils = new Person("Nils");

    pl.settInnPerson(Emil);        //this populates the list
    pl.settInnPerson(Nils);

    }

}

而且仍然不起作用。

对象的范围在主方法中。 如果要在其外部使用它,请将其声明为TestPersoner类的成员,或将其作为参数传递给方法。

Local variables仅限于方法范围。 您不能在定义它们的方法之外使用它们。它们仅在方法完成后获得GC'D,除非您明确返回它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM