![](/img/trans.png)
[英]In Java, if a child class shadows a static parent variable with an instance child variable, which variable will inherited methods use?
[英]Java: Use Static methods of Parent Class in Child Class
我試圖通過使用BaseComponentType
類並在我的ElectricalComponentType
類(和類似的子類)中繼承我的代碼來重構我的代碼,如下所示:
public abstract class BaseComponentType {
public static BaseComponentType findByUid ( Class klass, String uid ) {
return new Select().from( klass ).where( "uid = ?", uid ).executeSingle();
}
}
public class ElectricalComponentType extends BaseComponentType {
public static ElectricalComponentType findByUid( String uid ) {
return (ElectricalComponentType) findByUid( ElectricalComponentType.class, uid );
}
}
我需要做的是調用ElectricalComponentType.findByUid( 'a1234' )
但如果我findByUid
在ElectricalComponentType
類中定義findByUid
而是從BaseComponentType
繼承此功能,那將會很棒。
你會發現有兩件事情在路上:
我需要findByUid
父方法中的ElectricalComponentType
類。
我需要返回ElectricalComponentType
對象(或者子類對象是什么)而不是BaseComponentType
類對象。
有沒有辦法做到這一點?
使用泛型並且只有父類方法:
public abstract class BaseComponentType {
public static <T extends BaseComponentType> T findByUid(Class<T> klass, String uid) {
return new Select().from( klass ).where( "uid = ?", uid ).executeSingle();
}
}
有幾點需要注意:
static
方法不被繼承,也不能被覆蓋; static
方法,首先必須編寫類名: BaseComponentType.findById()
; 如果你想在子類中刪除具有相同名稱的方法,你可能想要使它成為非靜態的或/並重新考慮你的類設計,因為如果在與繼承關系綁定的類中有兩個具有相同名稱的靜態方法,很可能是課堂設計有問題。
我希望你需要像以下一樣的東西..
public class TestClass{
public static void main(String args[]){
Child c2;
c2 = (Child) Child.findByUid(Child.class, "123");
System.out.println(c2.getClass());
}
}
class Base{
public static Base findByUid ( Class klass, String uid ) {
System.out.println(klass);
Child c = new Child();
//execute your query here and expect it to return the type of object as the class by which it was called
//your parent class method always returns the type of the child by which the method was called
return c;
}
}
class Child extends Base{
/*public static Child findByUid( String uid ) {
System.out.println(Child.class);
return (Child) findByUid( Child.class, uid );
}*/
}
我認為你可以重新設計這個,以便你有一個找到Component
的ComponentFinder
類。
public class ElectricalComponent extends Component {
@Override
public void method1(){
//specific stuff
}
}
public abstract class Component{
public abstract void method1();
}
public class ComponentFinder{
public static Component findByUid ( Class klass, String uid ) {
return new Select().from( klass ).where( "uid = ?", uid ).executeSingle();
}
}
然后您不必擔心繼承問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.