在java的子类方法中不能访问抽象类对象的属性
我想为不同的数据结构(如树、列表、数组等)编写一些不同的算法。除方法参数外,数据结构的方法90%相同在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>
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;
...
}