Java - Generic Static Methods -


i have been trying understand whether possible make method infers generic type based on return class , calls static method of generic type.

i.e. below create 2 classes both of implement getinstances , getallinstances methods. attempt create use methods generic wrapper. appears super class method being run regardless of return type.

for example,

public class parentclass {      public parentclass(){}      public static <t extends parentclass> t getinstance(){         return (t) new parentclass();     }      public static <t extends parentclass> list<t> getallinstances(){         arraylist<parentclass> parents = new arraylist<parentclass>();          for(int i=0;i<5;i++){             parents.add(new parentclass());         }          return (list<t>) parents;     }  } 

subclassa

public class subclassa extends parentclass{       public subclassa(){}      @suppresswarnings("unchecked")     public static subclassa getinstance(){          return new subclassa();     }      @suppresswarnings("unchecked")     public static list<subclassa> getallinstances(){         arraylist<subclassa> parents = new arraylist<subclassa>();            for(int i=0;i<5;i++){              parents.add(new subclassa());           }           return parents;       }  } 

wrapper - shows problem

 public class wrapper {      public wrapper(){         // ... other stuff     }      public <t extends parentclass> t getinstance(){         return t.getinstance();     }      public <t extends parentclass> list<t> getallinstances(){         return t.getallinstances();     }      public static void main(string... args){         wrapper wrapper = new wrapper();          subclassa subclassa = wrapper.getinstance();         parentclass parentclass = wrapper.getinstance();          system.out.println(subclassa.getclass().getname());         system.out.println(parentclass.getclass().getname());     }   } 

when running wrapper following error:

exception in thread "main" java.lang.classcastexception: parentclass cannot cast subclassa @ wrapper.main(wrapper.java:20)

can in java?

your approach incorrect, there no notion of static inheritance in java inheritance in context of object level. member methods (non-static) can inherited sub classes having appropriate access modifiers.

update: further add, in scenario factory pattern seems more suitable adjusting generics getting/constructing specific class objects.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -