0

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];
3
  • Type item = Type.newInstance(); Commented Mar 29, 2012 at 13:37
  • Have a look at "Why doesn't Java allow overriding of static methods?" stackoverflow.com/q/2223386/1250303 Commented Mar 29, 2012 at 13:38
  • @AlexeiKaigorodov That's not going to work for an arbitrary type. Commented Mar 29, 2012 at 13:53

1 Answer 1

1

I found that static methods are not overriding.

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 your processObject method, which you can use to create instances of Type from by calling newInstance() on it:

public void processObject(Map<?, ?> map, Class<Type> cls) {
    // Uses the no-args constructor of Type to create a new instance
    Type item = cls.newInstance();

    // ...
}

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 of BaseItem that you'd want to use for this.

public interface Factory<T> {
    T create();
}

// ...

public void processObject(Map<?, ?> map, Factory<Type> factory) {
    // Calls the factory to create a new Type
    Type item = factory.create();

    // ...
}

// Factory implementation for BaseItem
public class BaseItemFactory implements Factory<BaseItem> {
    @Override
    public BaseItem create() {
        return new BaseItem();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

An explicit factory is by far the best way to do this.
I've solved this problem by extracting superclass for BaseArrayList - So I've abstract BAArrayList<Type extends BaseItem> with abstract method newObject();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.