为什么这个班级是抽象的?

时间:2013-03-21 21:19:08

标签: java optimization

在我的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 + "}";
     }
}

2 个答案:

答案 0 :(得分:8)

由于AbstractGrid<E>实现Grid<E>,但未实现其所有方法,因此必须将其声明为abstract

abstract的任何非AbstractGrid<E>子类都需要实现这些方法。

答案 1 :(得分:0)

该类是抽象的,因为多种类型的“Grid”类继承自它。虽然AbstractGrid包含常见的方法/变量,但它本身不能起作用。因此,它是抽象的。

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