java构造函数调用构造函数

java构造函数调用构造函数时,通过保留字this调用本类其他构造函数,super调用父构造函数。并且调用必须置于该构造函数的首句。
错误的写法:

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规则的限制,我们的做法是相反的,即在一个带有多参数的函数中实现所有的条件和功能,构造一个参数较少的构造函数对复杂的函数进行调用,传入一个特定的参数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值