java属性方法执行顺序

 

样题一

class P {

    private int val = 10;

 

    public void output() {

        System.out.println("P.output(),val+" + val);

    }

 

    public P() {

        System.out.println("P constructor");

        output();

    }

}

 

public class A extends P {

    private int val = 1;

 

    public void output() {

        System.out.println("A.output(),val=" + val);

    }

 

    public A(int val) {

        this.val = val;

        System.out.println("A constructor");

    }

 

    public static void main(String[] args) {

        A a = new A(5);

    }

}

答案:P constructor  A.output(),val=0  A constructor

 

样题二

 

class parent {

    public parent() {

        System.out.println("parent...");

    }

}

 

class child extends parent {

    brother b = new brother();

    public child() {

        System.out.println("child...");

    }

 

}

 

class brother {

    public brother() {

        System.out.println("brother...");

    }

}

 

public class Testchild {

 

    /**

     * @param args

     */

    public static void main(String[] args) {

        System.out.println(new child());

 

    }

 

}

答案:parent...  brother...  child...

 

结论:属性的优先级高于方法,父类构造方法高于自身构造方法,重写父亲类的方法高于本身属性执行 。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值