在java的子类方法中不能访问抽象类对象的属性

在java的子类方法中不能访问抽象类对象的属性,java,algorithm,abstract-class,Java,Algorithm,Abstract Class,我想为不同的数据结构(如树、列表、数组等)编写一些不同的算法。除方法参数外,数据结构的方法90%相同 public class BinaryTreeNode<T> { public T key; public BinaryTreeNode<T> leftChild; public BinaryTreeNode<T> rightChild; public boolean find(BinaryTreeNode<T>

我想为不同的数据结构(如树、列表、数组等)编写一些不同的算法。除方法参数外,数据结构的方法90%相同

public class BinaryTreeNode<T> {
    public T key;
    public BinaryTreeNode<T> leftChild;
    public BinaryTreeNode<T> rightChild;

    public boolean find(BinaryTreeNode<T> root, T key) { /* implementation */ }
}

public class ListItem<T> {
    public T key;
    public ListItem<T> next;

    public boolean find(ListItem<T> root, T key) { /* implementation */ }
}
但是它感觉编码不好,因为我必须创建一个临时的
ListItem
来转换
DataStruct
以访问
ListItem
的类属性


有更好的方法吗?

因为
find
方法不是
静态方法,所以它接受
DataStruct
对象并对该对象执行搜索是没有意义的。对自身执行搜索更有意义,这样就无需强制执行任何内容:

public boolean find(T key) {
    ListItem<T> tmpListItem = this;
    while(tmpListItem.next != null) {
        if(tmpListItem.key.equals(key))
           return true;
        tmpListItem = tmpListItem.next;
    }
}

为什么
ListItem
find
方法需要
DataStruct ListItem
参数?它是否应该在自身上执行搜索(即
)?这是上面的一些先决条件(练习表)。使用返回类型
boolean
和这两个参数实现方法
find
。也许这样做不是“最佳实践”。在仔细考虑了您的评论之后,我发现
DataStruct
参数确实是多余的。使用
this
解决了我遇到的所有问题。(对于接口定义,我更喜欢
interface
而不是
class
)(不定义
find()
,而是
Map.get()
List.indexOf()
是我对Java集合框架的不满之一。)请添加。因此,
接口
更好,因为我没有实现任何方法?但是我仍然需要一个超类,比如
DataStruct
,对吗?我不明白你的第二句话。你这是什么意思?还向
find
方法添加了一些JavaDoc。这甚至回答了我最初的问题。非常感谢你的回答/帮助。
public class ListItem<T> extends DataStruct<T> {
    public T key;
    public ListItem<T> next;

    @Override
    public boolean find(DataStruct<T> listItem, T key) {
        ListItem<T> tmpListItem = (ListItem<T>) listItem;
        while(tmpListItem.next != null) {
            if(tmpListItem.key == key)
               return true;
        }
    }
}
public boolean find(T key) {
    ListItem<T> tmpListItem = this;
    while(tmpListItem.next != null) {
        if(tmpListItem.key.equals(key))
           return true;
        tmpListItem = tmpListItem.next;
    }
}
public boolean find(DataStruct<T> listItem, T key) {
    if (!(listItem instanceof ListItem)) {
        // decide whether to return false or throw an exception
    }
    ListItem<T> tmpListItem = (ListItem<T>) listItem;
    ...
}