简体   繁体   English

Getter 返回旧值

[英]Getter returning old value

I recently ran into an issue with my object initialization.我最近遇到了对象初始化的问题。

I have a class (It is set up this way for persistent data storing and loading)我有一个类(它以这种方式设置用于持久数据存储和加载)

public class Example extends SuperExample{
    private String name = "";
    public Example(){
        super();
    }

    public String getName(){
        return name;
    }

    @Override
    protected void load(){
        name = "Example";
    }
}

public abstract class SuperExample{
    protected abstract void load();
    public SuperExample(){
        //Do stuff
        load();
    }
}

The getName() that is called after the object is initialized is returning "" and not "Example" .在对象初始化后调用的getName()返回""而不是"Example"

Any idea what the root cause of this could be?知道这可能是什么根本原因吗? If I were to set name in the constructor it works fine.如果我要在构造函数中设置name ,它工作正常。 But when it goes through the super , it errors.但是当它通过super ,它会出错。

Example e = new Example();
System.out.println(e.getName());

The initializer code: private String name = "";初始化代码:private String name = ""; runs AFTER the parent constructor.在父构造函数之后运行。 Remove the initialization and it will work correctly.删除初始化,它将正常工作。 But you shouldn't call overridable methods from constructors.但是您不应该从构造函数调用可覆盖的方法。 :) :)

private String name;

instead of代替

private String name="";

It's because the Example class method is protected I think.这是因为我认为 Example 类方法是受保护的。 It's not callable from outside the class, so you're calling the superclass method.它不能从类外部调用,因此您正在调用超类方法。 That does nothing so the value is still "" .那什么都不做,所以值仍然是"" To check this, add a print statement to the load method and see if it's being called.要检查这一点,请在 load 方法中添加一条打印语句并查看它是否被调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM