这是今天看视频时敲代码遇到的一个问题,做个记录。No enclosing instance of type Server is accessible. Must qualify the allocation with an enclosing instance of type Server。
public class Server{
public static void main(String[]args) throws IOException {
ServerSocket server=new ServerSocket(8080);
Socket client=server.accept();
MyChannel channel=**new MyChannel(client);**//此处报错
...
}
public class MyChannel implements Runnable{//内部类,可以方便访问外部类成员属性和成员方法
public DataInputStream dis;
public DataOutputStream dos;
public boolean isRunning=true;
}
}
报错的原因是调用创建内部类实例的方法错误。
内部类是依附外部类存在的,想要创建内部类对象,必须先要有一个外部类的对象
public class Server{
public static void main(String[]args) throws IOException {
ServerSocket server=new ServerSocket(8080);
Socket client=server.accept();
Server server=new Server();
Server.MyChannel channel=server.new MyChannel();//只有通过Server对象来创建。这样就创建了一个内部类对象
}
public class MyChannel implements Runnable{//内部类,可以方便访问外部类成员属性和成员方法
public DataInputStream dis;
public DataOutputStream dos;
public boolean isRunning=true;
...
}
}
通过外部方法创建成员内部类对象。
public class Server{
public static void main(String[]args) throws IOException {
ServerSocket server=new ServerSocket(8080);
Socket client=server.accept();
new Server().creat();
}
public void creat(){
MyChannel channel=new MyChannel();
}
public class MyChannel implements Runnable{//内部类,可以方便访问外部类成员属性和成员方法
public DataInputStream dis;
public DataOutputStream dos;
public boolean isRunning=true;
...
}
}
当然还可以把这个内部类放到外类去,等等,解决问题的方法有很多。。。