简体   繁体   中英

Accessing subclass-methods in ArrayList from ParentClass

At the moment my class looks something like this (very simplified):

I have three classes to describe either Nodes or Ways (from OpenStreetMap):

public abstract class Geometry {
    private String id;

    public Geometry(String id) {
        this.id = id;
    }
}

public class Node extends Geometry {
    private GeoPoint location;

    public Point(String id, GeoPoint location) {
        super(id);
        this.location = location;
    }
    public GeoPoint getLocation() {
        return location;
    }
}


public class Ways extends Geometry {
    private ArrayList <GeoPoint> shape;

    public Point(String id, ArrayList <GeoPoint> shape) {
        super(id);
        this.shape = shape;
    }
    public GeoPoint getShape() {
        return shape;
    }

}

Now I want to iterate through an ArrayList with the class Geometry and use methods from both subclasses:

private void prepareList(ArrayList<Geometry> geometries) {
    for (Geometry m : geometries) {
         if (m.getClass().equals(Node.class)) {
             location = m.getLocation();
         }
         else if (m.getClass().equals(Way.class)) {
             shape = m.getShape();
         }
    }
}

In my solution, I need to make some dummy methods in the class Geometry to access these methods, like public GeoPoint getLocation() { return null; }

My question now is, what is the best way to implement this in Java, without making separate classes (which leads to code duplicates) or writing this "dummy" methods. Is there a better way?

If I'm understanding your question correctly, you could simply declare an abstract method on Geometry that is implemented by the Node and Ways sub-classes.

public abstract class Geometry {
    private String id;

    public Geometry(String id) {
        this.id = id;
    }

    public abstract GeoPoint getLocation();
}

or consider making Geometry an interface. Something like:

public interface Traversable { 

    public String getId();

    public GeoPoint getLocation();

}

and implement this interface on Ways and Nodes . I would prefer the latter approach, as a class can implement multiple interfaces, but can only extend one super class.

EDIT : It's a little clearer to me now that you are not returning the same thing from Ways and Nodes . You could:

  • Wrap the results in a class that can deal with a single GeoPoint vs a List of GeoPoints
  • Re-work this code to perform whatever operation they Way or Node needs to perform inside of the sub-class.
  • Use a List of GeoPoints as the return type of the method, and a node only has one element that is returned vs many points returned by a Way

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM