美文网首页
默认构造器

默认构造器

作者: 海豚的小小海 | 来源:发表于2016-07-29 20:31 被阅读0次

    默认构造器(又名“无参”构造器)是没有形式参数的——它的作用是创建一个“默认对象”。如果类里面没有构造器,编译器就会自动帮你创建一个默认构造器。

    class Bird {}
    public class DefaultConstructor83 {
      public static void main( String[] args ) {
        Bird b = new Bird();    //
       }
    }```
    
    ```java 
    Bird b = new Bird(); 就是调用默认构造器——即使没明确定义它。
    

    如果已经定义了一个构造器(无论是否有参数),编译器就不会帮你自动创建默认构造器:

    class Bird2 {
      Bird2( int i ) {}
      Bird2( double d ) {}
    }
    public class NoSynthesis83 {
      public static void main( String[] args ) {
      //Bird2 b1 = new Bird2(); //No default 
      Bird2 b2 = new Bird2( 1 );
      Bird2 b3 = new Bird2( 2.33 );
      }
    }```
    这里必须用 **Bird b2 = new Bird()**, 如果是 **new Bird()** 就会报错。

    相关文章

      网友评论

          本文标题:默认构造器

          本文链接:https://www.haomeiwen.com/subject/gtizjttx.html