java构造函数调用构造函数时,通过保留字this调用本类其他构造函数,super调用父构造函数。并且调用必须置于该构造函数的首句。
错误的写法:
正确的写法:
注意,正确的写法与我们正常的编写一个方法的不同,按照习惯,我们喜欢通过一些判断,调用一个简单的重载方法。
还是实现以上功能我们一般写法是这样的:
对于普通方法,我们习惯实现一个简单的方法,通过增加一些判断条件,对原有方法进行重载。
而对于构造函数,由于java规则的限制,我们的做法是相反的,即在一个带有多参数的函数中实现所有的条件和功能,构造一个参数较少的构造函数对复杂的函数进行调用,传入一个特定的参数。
错误的写法:
public PropertiesLoader(String path){
prop = new Properties();
File file = new File(path);
InputStream is;
try {
is = new FileInputStream(file);
prop.load(is);
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
public PropertiesLoader(String path , boolean absolute){
if(!absolute)
path = System.getProperty("user.dir") + File.separator + path ;
this(path);//Constructor call must be the first statement in a constructor
//If you follow the norms, would be unable to achieve the desired effect.
}
正确的写法:
public PropertiesLoader(String path){
this(path,true);//Constructor call must be the first statement in a constructor
}
public PropertiesLoader(String path , boolean absolute){
if(!absolute)
path = System.getProperty("user.dir") + File.separator + path ;
prop = new Properties();
File file = new File(path);
InputStream is;
try {
is = new FileInputStream(file);
prop.load(is);
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
注意,正确的写法与我们正常的编写一个方法的不同,按照习惯,我们喜欢通过一些判断,调用一个简单的重载方法。
还是实现以上功能我们一般写法是这样的:
public Properties loader(String path){
Properties prop = new Properties();
File file = new File(path);
InputStream is;
try {
is = new FileInputStream(file);
prop.load(is);
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
} catch (IOException e) {
System.err.println(e.getMessage());
}
return prop;
}
public Properties loader(String path , boolean absolute){
if(!absolute)
path = System.getProperty("user.dir") + File.separator + path ;
return loader(path);
}
对于普通方法,我们习惯实现一个简单的方法,通过增加一些判断条件,对原有方法进行重载。
而对于构造函数,由于java规则的限制,我们的做法是相反的,即在一个带有多参数的函数中实现所有的条件和功能,构造一个参数较少的构造函数对复杂的函数进行调用,传入一个特定的参数。