从构造函数调用方法 [英] Calling method from constructor
问题描述
不要使用任何小的语法错误或什么,我遇到这个与Jitsi模块,不熟悉Java想要确认是什么,为什么和如何修复。
Excuse any minor syntax errors or whatnot, I'm experiencing this with a Jitsi module and not being super familiar with Java want to confirm what is going on and why and how it should be fixed.
public abstract class A
{
public A()
{
this.load();
}
protected void load()
{
}
}
public class B extends A
{
private String testString = null;
public B()
{
super();
}
@Override
protected void load()
{
testString = "test";
}
}
应用程序正在创建B类使用按名称方法的加载类方法:
The application is doing this when creating an instance of the class B using a load class by name method:
- 在类B中调用覆盖load()
- 初始化变量(根据调试器调用private string testString = null),将其置零。
什么原因可能导致?
推荐答案
这是期望的Java行为吗? / p>
Is this expected Java behavior?
是的。
?
What could cause this?
您在非最终超类构造函数中调用非最终重写的方法。
Your invocation of non-final overridden method in non-final super class constructor.
让我们一步一步看看会发生什么:
Let's see what happens step-by-step:
- 实例
B
。 -
code> A()
,以初始化超类成员。 -
现在调用在
B
类中重写的非最终方法作为初始化的一部分。 - 由于上下文中的实例是
B
类,调用的方法load()
是B
class。 -
load()
初始化B
字段 -testString
。 - 超类构造函数完成作业,并返回(假设构造函数链接到
Object 类已完成)
-
B()
构造函数开始执行,初始化它自己的成员。 - 现在,作为初始化过程的一部分,
B
会覆盖testString
,并将其重新初始化为null
。
- You create an instance of
B
. B()
calls super class constructor -A()
, to initialize the super class members.A()
now invokes a non-final method which is overridden inB
class, as a part of initialization.- Since the instance in the context is of
B
class, the methodload()
invoked is ofB
class. load()
initializes theB
class instance field -testString
.- The super class constructor finishes job, and returns (Assuming chaining of constructor till
Object
class have been finished) - The
B()
constructor starts executing further, initializing it's own member. - Now, as a part of initilization process,
B
overwrites the previous written value intestString
, and re-initializes it tonull
.
em> Moral:不要在其构造函数中调用非最终类的非最终公共方法。
Moral: Never call a non-final public method of a non-final class in it's constructor.
这篇关于从构造函数调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!