2015-07-20 183 views
-1

为什么:
如果一个类不提供任何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(); 
    } 
} 

控制台错误:

enter image description here

当我只调用了parameterized constructor。它的工作很好,但是当想用parameterized constructor调用default constructor。编译器给出编译错误,如图所示。

任何即时帮助将非常可观。谢谢

+3

嗯,所以提供你自己的无参数构造函数 - 就这么简单。如果没有明确提供,编译器* only *提供了一个默认构造函数。 –

+0

这是一个(非常)精确重复的http://stackoverflow.com/questions/11792207/why-does-the-default-parameterless-constructor-go-away-when-you-create-one-with - 那应该有你想要的信息 –

+0

@JonSkeet,我完全同意你的看法。我只想知道为什么? –

回答

5

您的问题的答案在您提供的段落中。

但如果一个类包含参构造函数,那么默认的构造函数不是由编译器提供

您创建了一个参数的构造函数,因此没有提供默认的非构造函数和theremore必须亲自使其

+0

我同意你的意见,我想知道为什么会发生这种情况?如果一个类包含参数化构造函数,那么为什么默认构造函数不是由编译器提供的? –

+0

查看链接@Razib发布(http://programmers.stackexchange.com/questions/257938/why-is-no-default-constructor-generated-if-you-define-an-explicit-constructor) –

1

如果你提供了一个构造函数,那么默认构造函数就不会被添加到你的类中。你必须自己定义它。

1

您正在编译使用javac ConstructorTest.java 而由于声明的参数的构造函数得到的错误 - public ConstructorTest(int x,int y)。因此,编译器不会为您的类提供任何默认构造函数[public ConstructorTest()]。所以你不能在第28行叫公共ConstructorTest()

+0

我同意你,我想知道为什么会发生这种情况?如果一个类包含参数化构造函数,那么为什么默认构造函数不是由编译器提供的? –

+0

@Rohit Jindal,你可能会看到链接 - http://stackoverflow.com/questions/16046200/why-java-doesnt-provide-default-constructor-if-class-has-parametrized-construc – Razib

1

我不知道你为什么问这个问题。你自己说过“但是如果一个类包含参数化构造函数,那么默认构造函数不是由编译器提供的。”......这样解释!

+0

我同意你的看法,我想知道为什么会发生这种情况?如果一个类包含参数化构造函数,那么为什么默认构造函数不是由编译器提供的? –