Java类和对象

值得思考的关于对象的一段代码

 private int i = giveMeJ();
    private int j = 20;

    private int giveMeJ() {
        return j;
    }

    public static void main(String[] args) {
        System.out.println("i: " + new InvalidValue().i);
    }

第一次看到这个,属实有些懵逼,第一感觉private声明的属性可以直接赋值?Google了一圈看到了关于这段代码的分析:
Java keeps the default constructor if no constructor is present, Hence let us keep the default constructor in the code to understand the code flow and value of i and j at each step
如果没有构造函数,就保持默认的构造函数

Follow this:

public class InvalidValue {
    private int i = giveMeJ();
    private int j = 20;

    // Default Constructor
    public InvalidValue() {
        super();
        // Second Print: inside Constructor[i= 0, j= 20]
        System.out.println("inside Constructor[i= " + i + ", j= " + j + "]");
    }

    private int giveMeJ() {
        // First Print: inside giveMeJ[i= 0, j= 0]
        System.out.println("inside giveMeJ[i= " + i + ", j= " + j + "]");
        return j;
    }

    public static void main(String[] args) {
        // Third Print: i: 0
        System.out.println("i: " + new InvalidValue().i);
    }

将代码稍微修改加上System.out.println()语句更方便的查看代码的执行顺序:

  1. Step 1: void main initiate the call by new InvalidValue().i,
  2. Step 2: i and j will be initiated by default value 0 then InvalidValue() constructor will be invoked and then super(); will be called,
  3. Step 3: Now the constructor (assign value to instance attributes) invokes private int i = giveMeJ(),
    4.Step 4: giveMeJ() method will be invoked and here value of i is 0 also value of j is 0, hence this method will return 0,
  4. step 5: i initialize by 0, now flow will go to private int j = 20,
  5. step 6: 20 value will be assigned to j,
  6. step 7: now the compiler will return to constructor (Step 3) and then it will print sysout statement (inside Constructor[i= 0, j= 20]),
  7. step 8: now compiler will return to void main() (Step 1) and it will print sysout statement (i: 0)

最终输出结果:

inside giveMeJ[i= 0, j= 0]
inside Constructor[i= 0, j= 20]
i: 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值