簡體   English   中英

Java:在子類中使用父類的靜態方法

[英]Java: Use Static methods of Parent Class in Child Class

我試圖通過使用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' )但如果我findByUidElectricalComponentType類中定義findByUid而是從BaseComponentType繼承此功能,那將會很棒。

你會發現有兩件事情在路上:

  1. 我需要findByUid父方法中的ElectricalComponentType類。

  2. 我需要返回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 );

    }*/
}

我認為你可以重新設計這個,以便你有一個找到ComponentComponentFinder類。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM