我是初学程序员,对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类型对象。但是,从我的理解,成员继承自Node,不允许传递Node?你是如何解决这个问题的?
EDIT1: 正如有人在评论中指出的那样,我试图通过将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;}
}
答案 0 :(得分:1)
因为Member继承了Node,所以你不能将Node类型对象传递给函数,因为Member已经继承了Node类
不,相反:您可以将Member
传递给带有Node
参数的方法。
以这种方式思考:您拨打root.get_member_id()
,但如果root
只是Node
而不是Member
,则它没有此方法。< / p>
答案 1 :(得分:0)
由于成员已经继承了Node类,因此无法将Node类型对象传递给函数吗?
没有。它的另一种方式。如果您将方法声明为
protected int validate_member(Node root, int member_id)
然后它会在输入中使用Member和Node。
对于前。考虑另一个类
public class Leaf extends Node{
Leaf不是会员,所以如果你创建了叶子的对象
Node leaf =new Leaf();
并尝试将此节点发送到
protected int validate_member(Member root, int member_id)
这是不正确的。所以这不可能。
如何解决此问题?
有两种方式。
覆盖Node中的方法并将左右变量添加到Member类(推荐)
public Node go_left() {return this.left;}
public Node go_right() {return this.right;}
到
public Member go_left() {return this.left;}
public Member go_right() {return this.right;}
protected Member left,right;
在调用方法(不安全)
时输入validate_member((Member)root.go_left(), member_id)