-4

我的主类中有一个默认构造函数,在运行时似乎没有被调用。这是一个例子:

public class Cat {
    private static int myval;

    Cat() throws IOException {
        this.myval = 7;
        System.out.println("Called constructor");
    }

    public static void main() {
        // Main program
    }
}

在运行时,我看不到窗口中输出的“调用构造函数”行。我敢肯定这是显而易见的!

提前谢谢了。

4

4 回答 4

2

首先,你没有main方法。

你的是public static void main()

尝试运行它,编译器会告诉你没有main.

在此处输入图像描述

其次,您没有实例化 Cat。试试这个修改后的类,你会正确看到输出:

public class Cat {
    private static int myval;

    Cat() throws IOException {
        this.myval = 7;
        System.out.println("Called constructor");
    }

    public static void main(String args[]) throws IOException {
        Cat c = new Cat();
    }
}

结果:

Called constructor
于 2013-04-21T11:38:46.253 回答
1

构造函数仍然需要被调用main。默认构造函数只是指尚未定义构造函数的类。您已经定义了一个构造函数,所以这只是一个无参数的构造函数。

查看Wikipedia文章,特别是 Java 和 C#。

此外,您创建的方法需要被捕获,因为它会引发异常。你的代码应该是这样的:

public class Cat {
    private static int myval;

    Cat() throws IOException {
        this.myval = 7;
        System.out.println("Called constructor");
    }

    public static void main() {
        try {
            Cat cat = new Cat()
        } catch (IOException e) {
            // do stuff with e
        }
    }
}

默认构造函数如下所示:

public class Cat { 
    private static int myval;

    public String meow() {
        return "Meow!";
    }
}

public class MainClass {
    public static void main(String[] argsv) {
        Cat cat = new Cat();
        System.out.println(cat.meow());
    }
}
于 2013-04-21T11:29:42.347 回答
0

好吧,您从来没有真正创建过您的类的实例吗?您必须在 main 方法中创建 Cat 类的实例。

public static void main(){
// Main program
new cat();// this will invoke your constructor call
}
于 2013-04-21T11:28:20.230 回答
0

Java 术语中的 Default 构造函数由 JVM 在不存在其他构造函数时生成。通过编写构造函数,它不再是默认构造函数!

此外,如前所述,您需要使用new关键字来调用Cat()构造函数。

于 2013-04-21T11:29:48.890 回答