跳过父构造函数来调用祖父母 [英] Jump over parent constructor to call grandparent's

查看:91
本文介绍了跳过父构造函数来调用祖父母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题在于:我有一个抽象类在其构造函数中执行一些工作,以及一组实现抽象类的子类:

The problem is this: I have an abstract class that does some work in its constructor, and a set of child classes that implement the abstract class:

class AbstractClass {
     AbstractClass(){ /* useful implementation */ }
}

class ConcreteClass1 extends AbstractClass {
     ConcreteClass1(){ super(); /* useful implementation */ }
}

然后,具体类需要定制一个解决方案是扩展具体类:

Then, the concrete classes need to be customized and one solution is to extend the concrete classes:

class CustomizedClass1 extends ConcreteClass1 {
    CustomizedCLass1(){ super(); /* useful implementation */ }
}

但问题是自定义类需要只调用抽象类的构造函数而不是具体类的构造函数。

BUT the problem is that the customized classes need only to call the abstract class's constructor and not the concrete class's constructor.

你是如何实现这一目标的?更改类关系的建议是有效的。

How do you achieve this? Suggestions to change the class's relationships are valid.

编辑:具体示例是ConcreteClass1和CustomizedClass1具有不同的数据集(ConcreteData1和CustomizedData1),并从中检索类的构造函数中的数据库。问题是创建CustomizedClass1的实例将检索两个数据实体。

The concrete example is that ConcreteClass1 and CustomizedClass1 have different sets of data (ConcreteData1 and CustomizedData1), and it is retrieved from the database in the class's constructor. The problem is that creating an instance of CustomizedClass1 will retrieve both data entities.

我知道使用简单的继承它可能不是最好的事情,这就是为什么我指出改变班级关系的建议是有效的。

I am aware that using simple inheritance it's probably not the best thing to do, that's why I pointed out that suggestions to change the class's relationships are valid.

推荐答案

容易(但为什么?):

class AbstractClass {
   AbstractClass(){ /* useful implementation */ }
}

class ConcreteClass1 extends AbstractClass {
     ConcreteClass1(){ super(); /* useful implementation */ }
     ConcreteClass1(boolean skip){ super(); }
}
class CustomizedClass1 extends ConcreteClass1 {
     CustomizedCLass1(){ super(true); /* useful implementation */ }
}

这篇关于跳过父构造函数来调用祖父母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆