美文网首页
无参构造器

无参构造器

作者: susu2016 | 来源:发表于2020-12-21 17:13 被阅读0次

    1、子类没有构造函数时,自动调用父类的无参构造函数

    public class Animal {
        Animal(){
            System.out.println("Animal NoArgsConstructor");
        }
    
        Animal(int a){
            System.out.println("Animal args construction");
        }
    }
    
    public class Bird extends Animal {
        public static void main(String[] args) {
            Animal animal = new Bird();
        }
    }
    

    运行结果:Animal NoArgsConstructor

    2、子类显示指定构造函数时,也会自动调用父类构造方法

    public class Bird extends Animal {
        Bird() {
            System.out.println("Bird NoArgsConstructor");
        }
    
        public static void main(String[] args) {
            Animal animal = new Bird();
        }
    }
    
    class Animal {
        Animal(){
            System.out.println("Animal NoArgsConstructor");
        }
    
        Animal(int a){
            System.out.println("Animal args construction");
        }
    }
    

    运行结果:Animal NoArgsConstructor
    Bird NoArgsConstructor

    3、父类没有无参构造函数时,子类缺省无参构造函数或者指定无参构造函数都会报错

    报错情况1:

    public class Bird extends Animal {
        Bird() {
            System.out.println("Bird NoArgsConstructor");
        }
    
        public static void main(String[] args) {
            Animal animal = new Bird();
        }
    }
    
    class Animal {
    
        Animal(int a){
            System.out.println("Animal args construction");
        }
    }
    

    报错情况2:

    public class Bird extends Animal {
        
        public static void main(String[] args) {
            Animal animal = new Bird();
        }
    }
    
    class Animal {
    
        Animal(int a){
            System.out.println("Animal args construction");
        }
    }
    

    相关文章

      网友评论

          本文标题:无参构造器

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