内部类

xiaoxiao2021-02-28  133

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

其相关代码如下:

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 {

              //省略代码

  }

转载请注明原文地址: https://www.6miu.com/read-19688.html

最新回复(0)