【发布时间】:2014-08-27 07:43:07
【问题描述】:
在《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();
}
}
【问题讨论】:
-
对于这个小玩具程序,真的没有优势。但是对于大多数其他不仅仅是琐碎的程序,main 方法应该非常小,并且大多数代码工作应该在实例域中完成,而不是在静态域中。
-
这可能是作者不喜欢使用
static。只要您需要多个方法来处理相同的数据,就必须声明类数据成员。如果您不创建对象实例,则所有内容都需要声明为static(如果您忘记了,则会出现令人困惑的错误)。 -
在构造函数中完成所有工作,吞下异常,而不是关闭流,是不好的做法。我也不会读那本书。
-
不幸的是,我从 1997 年就开始学习 Java。所以我已经很久没有阅读 Java 入门书籍了。有人告诉我,Bruce Eckel 的 Thinking in Java 非常好。
-
是的,将“实际函数”放在构造函数中通常是个坏主意,而不是(在这种情况下)将它放在
main或doit实例方法中。对于“玩具”程序来说没有什么大不了的,但将代码放入构造函数中也没有真正意义。
标签: java constructor main