[英]Java - Instance variable is dependent on Constructor argument
I want to set a variable which is dependent on the argument passed to the constructor.我想设置一个依赖于传递给构造函数的参数的变量。 At the moment my code looks something like this.
目前我的代码看起来像这样。 Is calling a method here bad practice and is there a better way of doing this?
在这里调用方法是不好的做法吗?有更好的方法吗? I have searched for an answer but haven't been able to find anything.
我一直在寻找答案,但一直找不到任何东西。 All help appreciated.
所有帮助表示赞赏。
public class Test {
int num;
public Test(int num) {
this.num = prime(num);
}
public int prime(int num) {
//code to get a prime number
}
}
Calling a method from constructor is bad practice if it is an overridable method.如果它是一个可重写的方法,那么从构造函数调用一个方法是不好的做法。 With overridable methods you get into initialisation order troubles.
使用可覆盖的方法,您会遇到初始化顺序的麻烦。 See this question .
看到这个问题。
You should make your prime()
method private, static or final.您应该将
prime()
方法设为私有、静态或最终。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.