-

2011年8月3日星期三

Does java still create a default constructor even in this case?

-MyClass m=new MyClass();//java provide a default constructor for this

MyClass m=new MyClass(3,2);//how about for this code?does java still provide a default constructor?I answered the same way to a question on stackoverflow and got smacked down pretty hard.



The actual situation is slightly more complicated. From the documentation linked below:



You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.



** back to me:

Since most user classes don't have an explicit superclass, thus being implicitly subclass of the Object class, then you do not have to provide a not argument constructor. After the aforementioned 'smack down' I wrote some code to test it and found out that it's true. If you write a little code to do your own test then you'll have confidence in the answer.

没有评论:

发表评论