Java: using static methods of the parent class in subclasses
•
Java
I tried to refactor my code by using the basecomponenttype class and inheriting my code in my electricalcomponenttype class (and similar subclasses), as follows:
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 ); } }
All I need to do is call electricalcomponenttype Findbyuid ('a1234 '), but it would be great if I didn't have to define findbyuid in the electricalcomponenttype class but inherited this function from basecomponenttype
You will find two things on the way:
>I need the electricalcomponenttype class in the parent method of findbyuid. > I need to return the electricalcomponenttype object (or what the subclass object is) instead of the basecomponenttype object
Is there any way to do this?
Solution
Use generic and only parent methods:
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(); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码