0

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
    }   
}
Abra
  • 19,142
  • 7
  • 29
  • 41
MR_P
  • 1
  • 1

1 Answers1

2

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.

keuleJ
  • 3,418
  • 4
  • 30
  • 51