【发布时间】:2014-05-03 17:05:06
【问题描述】:
我正在尝试使用BaseComponentType 类重构我的代码,并在我的ElectricalComponentType 类(和类似的子类)中继承此代码,如下所示:
BaseComponentType.java
public abstract class BaseComponentType {
public static BaseComponentType findByUid ( Class klass, String uid ) {
return new Select().from( klass ).where( "uid = ?", uid ).executeSingle();
}
}
ElectricalComponentType.java
public class ElectricalComponentType extends BaseComponentType {
public static ElectricalComponentType findByUid( String uid ) {
return (ElectricalComponentType) findByUid( ElectricalComponentType.class, uid );
}
}
我需要做的是调用ElectricalComponentType.findByUid( 'a1234' ),但如果我不必在ElectricalComponentType 类中定义findByUid 而是可以从BaseComponentType 继承此功能,那就太好了。
您会注意到有两件事阻碍:
我需要
ElectricalComponentType父方法中的ElectricalComponentType类。我需要返回
ElectricalComponentType对象(或任何子类对象)而不是BaseComponentType类对象。
有没有办法做到这一点?
【问题讨论】:
-
“删除”findByUid 方法是什么意思?不能直接删除吗?而且您的抽象类似乎没有任何抽象方法,因此您不必“必须”覆盖任何东西。这里的动机是什么?
-
如果您的 ElectricalComponentType 中不需要 findByUid 方法,那您为什么要在那里编写呢?我敢说删除它的最好方法是从一开始就没有对其进行编程。
-
您可能想看看这里:stackoverflow.com/questions/10291949/… 或右侧任何其他关于静态方法和继承的讨论。
-
“删除”是指我不想在
ElectricalComponentType模型中定义它,但我仍然需要在ElectricalComponentType.findByUid( 'a433' )中进行。我会稍微更新一下问题。 -
@JoshPinter 您不需要覆盖除抽象方法(您未在示例中定义)之外的任何方法。
标签: java inheritance abstract-class static-methods