Java - 在范围内无法访问类型的封闭实例

时间:2014-05-27 16:18:03

标签: java

我有这堂课:

public class PetAssembly extends Global
{
    public Socket socket;
    public ConnectionManager user;

    public PetAssembly(Socket socket, ConnectionManager user)
    {
        this.socket = socket;
        this.user = user;
    }

    public void initPet()
    {
        sendPacket(socket, "0|PET|I|0|0|1");
        sendPacket(socket, "0|PET|S|1000|1|0|8000|50000|50000|1000|1000|50000|50000|" + (((user.user.getSpeed() * 30) / 100) + user.user.getSpeed()) + "|testPet");
    }
}

我想用它:

case "/pet":
      PetAssembly.this.initPet();
break;

但它给了我这个错误,如何解决?我是初学者:No enclosing instance of the type PetAssembly is accessible in scope

1 个答案:

答案 0 :(得分:4)

PetAssembly.initPet()是一个实例方法。首先需要构造一个PetAssembly对象(该类的一个实例),然后在对它调用方法之前先引用该对象。

PetAssembly pa = new PetAssembly(socket, user); 
// Creates a new PetAssembly object
// and stores a reference to that in the variable pa.
pa.initPet(); 
// Calls the initPet() method on the PetAssembly object referred to by the variable pa.