2013-03-13 105 views
4

有一类U1,这是继承类U. U类是空的......构造函数this()不必要?

在U1的构造有这行头,父类的构造函数...

public U1(Plate plate, int order) 
{ 
    super(plate, order); 
... 

} 

现在我想要删除U1类,并在U类中做到目前为止在U1中做的任何事情...... 因此,现在我不需要调用超类的构造函数,因为U类不会有任何超类...

this(plate, order)是不必要的,我可以省略它吗?

这是我的U形构造是怎么会是这样的:

public U(Plate plate, int order) 
    { 
     this(plate, order); 
    ... 

    } 

回答

8

这是不必要的,我希望它会导致堆栈溢出,因为您从构造函数中调用构造函数本身。

+2

事实上,它甚至没有获得远远不够是一个堆栈溢出。它永远不会运行。 – 2013-03-13 08:41:11

0

不是你可以忽略它。你必须忽略它,否则它会作为一个永不结束的递归调用。

7

这会导致编译错误。 JLS section 8.8.7说:

"It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this ."

在这种情况下,构造函数直接调用自己。

+2

+1,很好! 'javac'确实会返回错误'递归构造函数调用'。 – 2013-03-13 08:40:41

0

我们在构造函数中调用super()以初始化从超类继承的实例变量,所以如果没有超类 - 不存在java.lang.Object,则不需要调用super()。 如果多构造函数在哪里,我们可以通过this()来调用其他构造函数,但不要自己调用构造函数,这会导致以前人们所称的坏事。

样品
1

如下,我们将得到错误:递归的构造函数调用,

class TestConstruct{ 
public TestConstruct(){ 
    this(); 
    System.out.println("constructor of Test class"); 
}//end of constructor 
}//end of class TestConstruct 
public class AppConstruct{ 
public static void main(String[] a){ 
Test t = new Test(); 
}//end of main 
}//end of AppConstruct