//接口X
interface X
{
public void run();
}
//实现接口X的一个类
class I implements X
{
X x;
public I()
{
this.x=new I(); //Exception in thread "main" java.lang.StackOverflowError
}
public I(X x)
{
this.x=x;
}
public void start()
{
x.run();
}
public void run()
{
}
}
//实现接口X的一个类
class A implements X
{
public void run()
{
System.out.println("A");
}
}
//继承类I的类
class B extends I
{
public void run()
{
System.out.println("B");
}
}public class Q
{
public static void main(String[] args)
{
new I(new A()).start();
new B().start();
}
}
为什么this.x=x;这句没有出错而this.x=new I(); 出错了?
java.lang.StackOverflowError是什么错误?
线程Thread类的构造函数Thread()和Thread(Runnable target)内部是怎么写的(想象)
public I()
{
this.x=new I(); //Exception in thread "main" java.lang.StackOverflowError
}
出现这个错误是因为你在构造方法中构造自己.....执行到这里会出现递归构造,最后stack益出.....
public I()
{ }
这样也会出像问题是为什么呢?