构造函数中的逻辑?

mad*_*dhu 4 java

下面的代码工作正常,但我想知道在对象创建时间是否有任何问题.

import java.util.Scanner;

public class FactorialExample {
    public FactorialExample(int n) {
        int fact=1;
        for(int i=1;i<=n;i++) {
              fact=fact*i;  
        }
        System.out.println("the factorial of a given number is::"+fact);        
    }
            public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any Integer Value:");
        int value=sc.nextInt();
        FactorialExample fe=new FactorialExample(value);

    }
}
Run Code Online (Sandbox Code Playgroud)

vik*_*eve 6

是的,你是在正确的假设 - 不要在构造函数中使用业务逻辑.

最多,初始化对象状态.

否则,异常处理,测试和模拟等问题就会变得困难.

在您的代码中,您可以完全避免使用构造函数,实际上:

import java.util.Scanner;

public class FactorialExample {
    int solve(int n){
        int fact=1;
        for(int i=1;i<=n;i++){
            fact=fact*i;
        }
        return fact;
    }

    public static void main(String[] args) {
        FactorialExample fe=new FactorialExample();
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter any Integer Value:");
        int value=sc.nextInt();
        int solution = fe.solve(value);
        System.out.println("tha factorail of a given number is::"+solution);
    }
}
Run Code Online (Sandbox Code Playgroud)