在“Sams Teach Yourself Java”一书中,作者经常在构造函数中编写一堆代码并将主块放在其外部,然后调用主块内的构造函数。这样做有什么好处,而不是像有些人那样在主块中编写代码吗?
示例:
import java.io.*;
import java.util.*;
class Configurator {
Configurator() {
try {
// load the properties file
File configFile = new File("program.properties");
FileInputStream inStream = new
FileInputStream(configFile);
Properties config = new Properties();
config.load(inStream);
// create a new property
Date current = new Date();
config.setProperty("runtime", current.toString());
// save the properties file
FileOutputStream outStream = new
FileOutputStream(configFile);
config.store(outStream, "Properties settings");
inStream.close();
config.list(System.out);
} catch (IOException ioe) {
System.out.println("IO error " + ioe.getMessage());
}
}
public static void main(String[] arguments) {
Configurator con = new Configurator();
}
}
答案 0 :(得分:3)
这本书因为非常糟糕而臭名昭着。但是在构造函数中有很多代码,构造函数意图构造'一个对象,比如设置对象的值等。不执行这么多任务,在类中创建构造函数可以调用的方法。
答案 1 :(得分:3)
就构造函数的质量而言,还有其他答案/评论解释了为什么这是一个坏主意。关于将所有代码专门放入构造函数而不是直接放在main
中,它在自动化测试和可移植性方面具有优势。
将所有代码移动到构造函数中允许自动化测试框架测试代码比测试main
更容易。此外,通过将整个应用程序放在没有主要内容的类中,您可以将其插入并在其他应用程序中使用。
答案 2 :(得分:0)
例如,main是一个静态方法,它只需要静态变量,因此编写大量代码并不好。