gpt4 book ai didi

java - 为什么这个类是抽象的?

转载 作者:行者123 更新时间:2023-12-01 07:10:24 26 4
gpt4 key购买 nike

在我的 AP 计算机科学类(class)中,我们已经学习了 GridWorld案例分析。在查看它时,似乎 AbstractGrid 类没有理由是抽象的,因为它没有抽象方法或值。为什么会这样?

更多信息

如果只是为了强制实现 Grid 接口(interface),为什么它不将这些方法作为抽象方法(从而在没有接口(interface)的情况下强制这些类的签名)。而且,无论如何,两个子进程都会重写它的大部分方法。

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

最佳答案

AbstractGrid<E>实现Grid<E> ,但没有实现其所有方法,必须声明 abstract .

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

关于java - 为什么这个类是抽象的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15558337/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com