运行程序,填写结果

public class Test {
    public static void main(String[] args) {
        System.out.println(new B().getValue());
    }
    static class A {
        protected int value;
        public A(int v) {
            setValue(v);
        }
        public void setValue(int value) {
            this.value = value;
        }
        public int getValue(){
            try {
                value++;
                return value;
            } finally {
                this.setValue(value);
                System.out.println(value);
            }
        }
    }
    static class B extends A {
        public B() {
            super(5);
            int aa=getValue();
            setValue( aa- 3);
        }
        public void setValue(int value) {
            super.setValue(2 * value);
        }
    }
}

结果是:

22

34

17

关键点:try---finally的返回的结果是try中的return那个值

本程序运行步骤如下:

new B()执行的步骤:

  1. super(5)→setValue(5)结果是:10

  2. getValue()→10+1=11→return11→setValue()11*2=22→打印22

  3. setValue(11-3)结果是:8*2=16

B.getValue()16+1=17→return 17→setValue()17*2=34→打印34→打印17

posted on 2018-04-16 09:34  lijingran  阅读(201)  评论(0编辑  收藏  举报

导航