今天周六没事就写点java方面的基础知识,平时在Q上也会有网友问我关于内部类报错方面的问题,如报这样的错误:
【
No enclosing instance of type TestThread is accessible. Must qualify the allocation with an enclosing instance of type TestThread (e.g. x.new A() where x is an instance of
TestThread).
】
或是:
【
Multiple markers at this line
- No enclosing instance of type TestThread is accessible. Must qualify the allocation with an enclosing instance of type TestThread (e.g. x.new A() where x
is an instance of TestThread).
- The value of the local variable tt is not used
】
其实这样的错误提示不是很明了,不太清楚,但你只要把握几点就不能出错:
在公共类(public claass xx {})中创建并使用内部类时无非有这两种形式:
1.
public class Test{
public static void main(String args[]){
TicketThread ticket = new TicketThread ();
new Thread (ticket).start();
new Thread (ticket).start();
new Thread (ticket).start();
}
private static class TicketThread implements Runnable{ //这里必须加上static 因为在main方法中要用到,且
//main方法是static的。若不在main方法中用可去掉
public void run(){
.....................
}
}
}
2.也可以这样来写:
public class Test{
public static void main(String args[]){
TicketThread ticket = new TicketThread ();
new Thread (ticket).start();
new Thread (ticket).start();
new Thread (ticket).start();
}
}
class TicketThread implements Runnabl{
public void run(){
.....................
}
}
总结:通常报以上两种错误提示的问题主要是因为没有处理好static 。
先写到这里,
更多交流、更多了解:
QQ:444084929 个人主页:http://www.huiqinbo.com