一段魔性的java代码

坐标,某大型互联网公司,有个小伙伴发来一段代码,因源码涉及公司,处理之后如下:

for (flag = true; father instanceof Son; father = ((Son) father).mfather) {}

苦思不得其解,于是写了个demo,测试结果之后分析如下:

package com.xicheng.validator;

/**
 * @author xichengxml
 * @date 2019/3/7 16:45
 */
public class Main {

    public static void main(String[] args) {
        Son son = new Son();
        son.mfather = new Son();
        magicCode(son, false);
        son.mfather = new Father();
        magicCode(son, false);
    }

    /**
     * 对这段魔性代码做个解释,进行了两个赋值操作,这个需要了解for循环的执行机制:
     * 第一个语句是赋值语句;第二个语句是判断语句,如果为true则一直执行,直到为false退出;
     * 第三个语句是赋值语句
     *
     * 所以上述的解释为:首先对flag赋值,然后判断father的类型,一直循环到不是son类型,把值
     * 赋给father
     * @param father
     * @param flag
     */
    private static void magicCode(Father father, boolean flag) {
        int count = 0;
        for (flag = true; father instanceof Son; father = ((Son) father).mfather) {
            count++;
        }
        System.out.println("loop times:" + count);
        System.out.println(flag);
        if (father == null) {
            System.out.println("null");
        } else {
            System.out.println(father.getClass());
        }
    }

    static class Father {

    }

    static class Son extends Father {
        Father mfather;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值