如果没有任何实例变量,我将如何为我的类编写构造函数?

bab*_*eps 1 java

我想编写一个不接受任何参数的构造函数,所以如果我没有实例变量,我将如何做到这一点,用于创建一个构造函数,我有实例变量,我知道java创建一个默认构造函数,如果我没有但我被告知这是一个糟糕的编程习惯???(新的课程)

public class Validator {
    public Validator() {
    }

    public String getString(Scanner sc, String prompt) {
        System.out.print(prompt);
        String s = sc.next(); // read user entry
        sc.nextLine(); // discard any other data entered on the line
        return s;
    }

    public int getInt(Scanner sc, String prompt) {
        int i = 0;
        boolean isValid = false;
        while (isValid == false) {
            System.out.print(prompt);
            if (sc.hasNextInt()) {
                i = sc.nextInt();
                isValid = true;
            } else {
                System.out.println("Error! Invalid integer value. Try again.");
            }
            sc.nextLine(); // discard any other data entered on the line
        }
        return i;
    }

    public int getInt(Scanner sc, String prompt, int min, int max) {
        int i = 0;
        boolean isValid = false;
        while (isValid == false) {
            i = getInt(sc, prompt);
            if (i <= min)
                System.out.println("Error! Number must be greater than " + min
                        + ".");
            else if (i >= max)
                System.out.println("Error! Number must be less than " + max
                        + ".");
            else
                isValid = true;
        }
        return i;
    }

    public double getDouble(Scanner sc, String prompt) {
        double d = 0;
        boolean isValid = false;
        while (isValid == false) {
            System.out.print(prompt);
            if (sc.hasNextDouble()) {
                d = sc.nextDouble();
                isValid = true;
            } else {
                System.out.println("Error! Invalid decimal value. Try again.");
            }
            sc.nextLine(); // discard any other data entered on the line
        }
        return d;
    }

    public double getDouble(Scanner sc, String prompt, double min, double max) {
        double d = 0;
        boolean isValid = false;
        while (isValid == false) {
            d = getDouble(sc, prompt);
            if (d <= min)
                System.out.println("Error! Number must be greater than " + min
                        + ".");
            else if (d >= max)
                System.out.println("Error! Number must be less than " + max
                        + ".");
            else
                isValid = true;
        }
        return d;
    }
}
Run Code Online (Sandbox Code Playgroud)

chr*_*her 7

构造函数用于"构建"对象.如果您没有需要设置的值,则不需要构造函数.您可能还想考虑让您的课程保持静态.静态意味着您不需要创建它的实例来访问它的方法.当类的实例不包含特定值时,这通常很有用,就像你的一样!