java 构造方法 重写,在构造函数中使用重写的方法的替代方法,Java

In a Java project I am coding I have ended up using methods that are overridden in constructors. Something like:

class SuperClass {

SuperClass() {

intialise();

}

protected void initialise() {

//Do some stuff common to all subclasses

methodA();

methodB();

}

protected abstract void methodA();

protected abstract void methodB();

}

class SubClass1() {

SubClass() {

super();

}

protected void methodA() { //Do something }

protected void methodB() { //Do something }

}

class SubClass2() {

SubClass() {

super();

}

protected void methodA() { //Do something else }

protected void methodB() { //Do something else}

}

I now realise, that although in my case it works fine, it is somewhat dangerous since SubClass methods are called on an object that has currently only been constructed as a SuperClass object (something that may be overlooked when new classes that extend SuperClass are added in the future). It also wouldn't work in c++ due to differences in how objects are created.

The only way I can think to get round this is to move the initialise method call down to the concrete classes constructor:

class SuperClass {

SuperClass() {

}

protected void initialise() {

methodA();

methodB();

}

protected abstract void methodA();

protected abstract void methodB();

}

class SubClass1() {

SubClass() {

super();

initialise();

}

protected void methodA() { //Do something }

protected void methodB() { //Do something }

}...

Is this the common way to over come this issue? It seems a shame (and easy to forget) that all further classes that extend SuperClass need to remember to call initialise().

I also found myself doing something similar in a more complicated situational that uses a Factory Method in a constructor, which is overridden in subclasses to decide which concrete class to implement. The only other way I can think to get round this and keep the design pattern as is, is to perhaps construct in a two phase process; i.e. construct with the bare minimum, and then call a second method to finish off the job.

解决方案

This is really not a good idea as your Subclass will not be properly constructed when its methodA() and methodB() are called. That would be very confusing for people extending the class. Recommend you use an abstract init() instead, as suggested by dlev in his/her comment.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值