加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么我的字段没有初始化为我给它的值

发布时间:2020-12-15 02:00:54 所属栏目:Java 来源:网络整理
导读:我有以下课程: public abstract class AClass { public AClass() { aMethod(); } abstract protected void aMethod();}public class SubClass extends AClass { private int x = 5; private static final int y = 6; @Override protected void aMethod() {
我有以下课程:

public abstract class AClass {

    public AClass() {
        aMethod();
    }

    abstract protected void aMethod();

}

public class SubClass extends AClass {

    private int x = 5;
    private static final int y = 6;

    @Override
    protected void aMethod() {
        System.out.println("x: " + x + " | y: " + y);
    }

}

public class Main {

    public static void main(String[] args) {
        new SubClass();
    }

}

Running Main打印以下内容:x:0 | y:6

为什么0打印x?

解决方法

不良行为的原因是错误的初始化序列:

> new SubClass()执行AClass构造函数
> AClass构造函数调用aMethod()
> aMethod()显示x(到目前为止为0),y为6,因为它是静态的)
> SubClass初始化其非静态字段,因此x变为5.

为避免惊慌失措,请不要在构造函数中调用虚方法(尤其是overriden)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读