gpt4 book ai didi

java - 遍历节点类被另一个类继承的树

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:27 24 4
gpt4 key购买 nike

我是初级程序员,对 Java 完全陌生。一切正常,除了我无法遍历这棵树。

public class Node extends Utility {
protected Node left;
protected Node right;

public Node() {this.left = null; this.right = null;}
public Node go_left() {return this.left;}
public Node go_right() {return this.right;}
public void connect_left(Node connection) {this.left = connection;}
public void connect_right(Node connection) {this.right = connection;}
}

public class Member extends Node{
protected String Name;
protected int id;

public Member() {
this.Name = null;
this.id = 0;
}

public Member(String Name, int id){
this.Name = Name;
this.id = id;
}

public int get_member_id() {return id;}

public String get_status() {return status;}
}

public class MemberList{
protected Member m_root;
public MemberList() {
this.m_root = null;
}

public int validate_member_wrapper (int member_id){
return validate_member(this.m_root, member_id);
}

protected int validate_member(Member root, int member_id) {
if(root == null)
return -1;
if(root.get_member_id() == member_id) {
if(root.get_status().compareToIgnoreCase("Active") == 0)
return 1;
else
return 0;
}

if(root.get_member_id() < member_id)
return validate_member(root.go_left(), member_id);
else
return validate_member(root.go_right(), member_id);

}
}

我尝试运行此代码,但出现错误提示我无法将对象类型 Node 转换为 Member。

validate_member(root.go_left(), member_id)

validate_member(root.go_left(), member_id)

不允许我传入 Node 类型的对象。但是,据我了解,Member继承自Node,不允许传递Node?你如何解决这个问题?

编辑1:正如有人在评论中指出的那样,我试图通过将 Node 类中的 go_left() 和 go_right() 函数覆盖到 Member 类来解决这个问题,但不知何故它显示了一个错误,指出 Node 无法转换为 Member。

这里是变化

public class Node extends Utility {
protected Node left;
protected Node right;

public Node() {this.left = null; this.right = null;}
public Node go_left() {return this.left;}
public Node go_right() {return this.right;}
}

public class Member extends Node{
protected String Name;
protected int id;

public Member() {
this.Name = null;
this.id = 0;
}

public Member(String Name, int id){
this.Name = Name;
this.id = id;
}

public Member go_left() {return this.left;}
public Member go_right() {return this.right;}

public int get_member_id() {return id;}

public String get_status() {return status;}
}

最佳答案

because Member inherited Node, couldn't you pass Node type object into the functions since Member already inherited Node class

不,恰恰相反:您可以将 Member 传递给带有 Node 参数的方法。

这样想:您调用 root.get_member_id(),但是如果 root 只是一个 Node 而不是 成员,没有这个方法。

关于java - 遍历节点类被另一个类继承的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50444916/

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