内部类

来源:互联网 发布:网站的优化 编辑:程序博客网 时间:2024/06/05 22:08

今天在使用内部类时出现一个小错误:

其相关代码如下:

public class ChatDemo {
class Send implements Runnable {
private DatagramSocket ds;

public Send(DatagramSocket ds) {
this.ds = ds;
}

@Override
public void run() {

//省略
}
}

class Rece implements Runnable {
private DatagramSocket ds;

public Rece(DatagramSocket ds) {
this.ds = ds;
}

@Override
public void run() {

//省略
}
}

public static void main(String[] args) throws Exception {
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket receSocket = new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();
}
}

其中在

        new Thread(new Send(sendSocket)).start();
new Thread(new Rece(receSocket)).start();

报错 No enclosing instance of type ChatDemo is accessible. Must qualify the allocation with an enclosing instance of type ChatDemo (e.g. x.new A() where x is an instance of ChatDemo).

查找资料发现,main方法是一个静态方法,不可以调用非静态的类,修改方法有两种:

1.将类用static修饰

static class Send implements Runnable {

//省略代码

}

2.将类放到外部去

class Rece implements Runnable {

//省略代码

        }

        class Rece implements Runnable {

              //省略代码

  }

原创粉丝点击