构造函数结束后调用方法 [英] Call a method after the constructor has ended
本文介绍了构造函数结束后调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
构造函数结束后,我需要调用一个方法,但我不知道该怎么做.我有这个课:
I need to call a method after the constructor has ended and I have no idea how to do. I have this class:
Class A {
public A() {
//...
}
public void init() {
//Call after the constructor
}
}
推荐答案
您要么必须在客户端执行此操作,
You either have to do this on the client side, as so:
A a = new A();
a.init();
否则您将必须在构造函数的末尾执行该操作:
or you would have to do it in the end of the constructor:
class A {
public A() {
// ...
init();
}
public final void init() {
// ...
}
}
但是,不建议使用第二种方法,除非您将方法设为私有或最终方法.
The second way is not recommended however, unless you make the method private or final.
另一种替代方法可能是使用工厂方法:
Another alternative may be to use a factory method:
class A {
private A() { // private to make sure one has to go through factory method
// ...
}
public final void init() {
// ...
}
public static A create() {
A a = new A();
a.init();
return a;
}
}
相关问题:
Related questions:
这篇关于构造函数结束后调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文