0

在我的 AP 计算机科学课上,我们一直在学习GridWorld案例研究。看着它,似乎 AbstractGrid 类没有抽象的理由,因为它没有抽象方法或值。为什么会这样?

更多信息

如果只是强制实现 Grid 接口,为什么不将这些方法作为抽象方法(因此在没有接口的情况下强制这些类的签名)。此外,无论如何,这两个孩子都会覆盖它的大部分方法。

package info.gridworld.grid;
import java.util.ArrayList;

public abstract class AbstractGrid<E> implements Grid<E>
{
    public ArrayList<E> getNeighbors(Location loc)
    {
        ArrayList<E> neighbors = new ArrayList<E>();
        for (Location neighborLoc : getOccupiedAdjacentLocations(loc))
            neighbors.add(get(neighborLoc));
        return neighbors;
    }

    public ArrayList<Location> getValidAdjacentLocations(Location loc)
    {
        ArrayList<Location> locs = new ArrayList<Location>();

        int d = Location.NORTH;
        for (int i = 0; i < Location.FULL_CIRCLE / Location.HALF_RIGHT; i++)
        {
            Location neighborLoc = loc.getAdjacentLocation(d);
            if (isValid(neighborLoc))
                locs.add(neighborLoc);
            d = d + Location.HALF_RIGHT;
        }
        return locs;
    }

    public ArrayList<Location> getEmptyAdjacentLocations(Location loc)
    {
        ArrayList<Location> locs = new ArrayList<Location>();
        for (Location neighborLoc : getValidAdjacentLocations(loc))
        {
            if (get(neighborLoc) == null)
                locs.add(neighborLoc);
        }
        return locs;
    }

    public ArrayList<Location> getOccupiedAdjacentLocations(Location loc)
    {
        ArrayList<Location> locs = new ArrayList<Location>();
        for (Location neighborLoc : getValidAdjacentLocations(loc))
        {
            if (get(neighborLoc) != null)
                locs.add(neighborLoc);
        }
        return locs;
    }

    /**
     * Creates a string that describes this grid.
     * @return a string with descriptions of all objects in this grid (not
     * necessarily in any particular order), in the format {loc=obj, loc=obj,
     * ...}
     */
     public String toString()
     {
         String s = "{";
         for (Location loc : getOccupiedLocations())
         {
             if (s.length() > 1)
                 s += ", ";
             s += loc + "=" + get(loc);
         }
         return s + "}";
     }
}
4

2 回答 2

8

由于AbstractGrid<E>implements Grid<E>,但没有实现其所有方法,因此必须声明它abstract

任何非子abstractAbstractGrid<E>都需要实现这些方法。

于 2013-03-21T21:24:24.430 回答
0

该类是抽象的,因为多种类型的“网格”类继承自它。虽然 AbstractGrid 包含常用方法/变量,但它不能单独运行。因此,它是抽象的。

去年必须参加这个考试,祝你好运=)

于 2013-03-21T21:26:53.283 回答