为什么:
如果一个类不提供任何constructors
然后default constructor(constructor without parameter)
由编译器在编译时给出,但如果一个类包含那么默认的构造函数不是由编译器提供。默认构造函数不调用
我在编译下面的代码。它给编译错误。
代码:
class ConstructorTest
{
// attributes
private int l,b;
// behaviour
public void display()
{
System.out.println("length="+l);
System.out.println("breadth="+b);
}
public int area()
{
return l*b;
}
// initialization
public ConstructorTest(int x,int y) // Parameterized Constructor
{
l=x;
b=y;
}
//main method
public static void main(String arr[])
{
ConstructorTest r = new ConstructorTest(5,10);
ConstructorTest s = new ConstructorTest();
s.display();
r.display();
r.area();
}
}
控制台错误:
当我只调用了parameterized constructor
。它的工作很好,但是当想用parameterized constructor
调用default constructor
。编译器给出编译错误,如图所示。
任何即时帮助将非常可观。谢谢
嗯,所以提供你自己的无参数构造函数 - 就这么简单。如果没有明确提供,编译器* only *提供了一个默认构造函数。 –
这是一个(非常)精确重复的http://stackoverflow.com/questions/11792207/why-does-the-default-parameterless-constructor-go-away-when-you-create-one-with - 那应该有你想要的信息 –
@JonSkeet,我完全同意你的看法。我只想知道为什么? –