使用“this”作为构造函数中方法调用的参数 [英] Using 'this' as a parameter to a method call in a constructor
问题描述
我有一个如下的构造函数:
public Agent(){
this。 name =John;
this.id = 9;
this.setTopWorldAgent(this,Top_World_Agent,true);
}
我在方法中得到一个空指针异常呼叫。这似乎是因为我使用'this'作为参数在setTopWorldAgent方法。通过删除这个方法调用一切似乎很好。为什么会发生这种情况?
你可以传递给方法,但setTopWorldAgent()不能是抽象的。您不能在构造函数中进行虚拟调用。
在对象的构造函数中,可以调用该对象中定义的方法,基类,但是你不能期望调用将由派生类提供的东西,因为派生类的部分尚未构造。如果setTopWorldAgent()是抽象的,我可能会遇到某种编译错误。
在Java中,你可以得到令人惊讶的行为, - 以下是一个示例
http: //en.wikipedia.org/wiki/Virtual_functions#Java_3
如果你习惯于C#或C ++,你可能认为调用虚函数是安全的而不是调用覆盖的。在Java中,即使派生类没有完全构造,也会进行虚拟调用。
如果这不是发生的事情,那么大概, setTopWorldAgent()需要被初始化 - 如果不是,它可能是需要初始化的成员之一。
编辑:认为这是C#
I have a constructor like as follows:
public Agent(){
this.name = "John";
this.id = 9;
this.setTopWorldAgent(this, "Top_World_Agent", true);
}
I'm getting a null pointer exception here in the method call. It appears to be because I'm using 'this' as an argument in the setTopWorldAgent method. By removing this method call everything appears fine. Why does this happen? Has anyone else experienced this?
You can pass this to methods, but setTopWorldAgent() cannot be abstract. You can't make a virtual call in the constructor.
In the constructor of an object, you can call methods defined in that object or base classes, but you cannot expect to call something that will be provided by a derived class, because parts of the derived class are not constructed yet. I would have expected some kind of compiler error if setTopWorldAgent() was abstract.
In Java, you can get surprising behavior with the contructor and derived classes -- here is an example
http://en.wikipedia.org/wiki/Virtual_functions#Java_3
If you are used to C# or C++, you might think it's safe to call virtual functions and not be calling overridden ones. In Java, the virtual call is made even though the derived class is not fully constructed.
If this isn't what's happening, then presumably, all of the parts of this that setTopWorldAgent() needs are initialized -- if not, it's probably one of the members of this that needs to be initialized.
Edit: thought this was C#
这篇关于使用“this”作为构造函数中方法调用的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!