简体   繁体   English

Java - 实例变量依赖于构造函数参数

[英]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.

相关问题 Java - 如何使用 3 参数构造函数来设置 2 个实例变量 - Java - How can I use a 3 argument constructor to set 2 instance variables 我如何编辑构造函数,使其采用单个双参数并将实例变量设置为该参数的值? - How do i edit a constructor so it takes a single double argument and sets an instance variable to the value of that argument? 如何将 object 类型作为参数传递给构造函数并将变量转换为它(JAVA)? - How to pass an object type to constructor as argument and cast a variable to it (JAVA)? 实例变量和构造函数 - Instance variable and constructor Java实例变量内部和外部构造函数的初始化混乱 - Java instance variable initialization inside and outside constructor confusion Java 如何使用超级 class 构造函数设置子 class 实例变量 - Java how to set child class instance variable with super class constructor 哈希集作为Java中的构造函数参数 - Hashset as constructor argument in Java 带有实例方法的 Java 构造函数 - Java constructor with instance methods 如何使用零参数构造函数创建具有通过Java反射绑定的上下文的Scala类的新实例? - How to create new instance of Scala class with context bound via Java reflection using only zero argument constructor? 无法构造java.util.LinkedHashMap的实例:no String-argument constructor / factory - Can not construct instance of java.util.LinkedHashMap: no String-argument constructor/factory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM