I’m new in Java.
I’m developing program for Android similar to app for iOS.
One of the purposes of app – is get data from server.
Data often is array with dictionaries like “id = 1”, “name = SomeName”.
I’ve class
class BaseArrayList<Type extends BaseItem> extends BaseItem {
public void processObject(Map<?,?> map) {
//......
//Some loop body
Type item = (Type) Type.create();
item.processObject(map);
//.....
}
Also BaseItem have method create():
public static BaseItem create() {
return new BaseItem();
}
It works, but for sublass of BaseItem -it doesn’t work.
I found that static methods are not overriding.
So, how I can resolve this task: create custom class in array with just creating custom instances of BaseArrayList such as:
new BaseArrayList<SomeSublassOfBaseItem>
This issue resolved in ObjC like this –
[[memberClass alloc] init];
Indeed, overriding does not work for static methods.
There are different ways to achieve what you want to do. One is to pass a
Class<Type>object to yourprocessObjectmethod, which you can use to create instances ofTypefrom by callingnewInstance()on it:Another more flexible way is to supply a factory to create instances of
Type. A disadvantage of this is that you’d need to implement a factory for each subclass ofBaseItemthat you’d want to use for this.