zoukankan      html  css  js  c++  java
  • Java构造器:级联调用,调用兄弟构造器

    级联调用:

    class Father{
        Father(){
            System.out.println("Father birth");
        }
        public void announce(){
            System.out.println("Father");
        }
    }
    class Child extends Father{
        Child(){
            System.out.println("Child birth");
        }
        @Override
        public void announce(){
            System.out.println("Child");
        }
    }
    public class Hello {
        public static void main(String[] args){
            Child child=new Child();
        }
    }

    上述代码的执行结果如下:

    Father birth
    Child birth

    我们可以看到,先执行了父类的构造器,然后执行子类的构造器。因此我们可以理解级联调用。

    级联调用指继承关系中子类构造器调用时会默认调用父类无参构造器作为子类构造器的第一句,除非子类构造器在第一句时显式的调用父类的其他构造器。

    需要说明的是,子类构造器第一句以外位置不能对父类构造器进行调用。

    调用兄弟构造器:

    class Test{
        Test(){
            System.out.println("Default initialize");
        }
        Test(int i){
            this();
            System.out.println("I have "+i+" as a parameter.");
        }
    }
    public class Hello {
        public static void main(String[] args){
            Test test=new Test(5);
        }
    }

    上述代码中的this就是一个调用兄弟构造器的例子,此处和级联调用类似,必须把调用语句放置在构造器的第一行。执行结果如下:

    Default initialize
    I have 5 as a parameter.

    Java严格的级联调用,兄弟调用顺序,保证了程序的易读性和规范性,并且方便了编译器对其进行实现。另外一旦使用了this()方法放置在第一行去调用兄弟构造器,则不再调用默认的无参父类构造器,而由调用的兄弟构造器去调用无参父类构造器,换言之,推迟了无参父类构造器的调用。

  • 相关阅读:
    基于注解的IOC配置
    字符串典型问题分析
    指针与数组
    数组的本质
    数组与指针分析
    指针的本质
    #与##操作符使用
    #pragma使用分析
    #error和#line使用分析
    条件编译使用
  • 原文地址:https://www.cnblogs.com/cielosun/p/6580936.html
Copyright © 2011-2022 走看看