我有子类Host
,它扩展了超类User
public abstract class User
{
public String user_name;
public String toString()
{
return this.getClass() + " Name: " + this.user_name;
}
}
class Host extends User
{
public Host(String user_name)
{
this.user_name=user_name;
}
public void test()
{
System.out.println(user_name + " pass");
}
}
在Main()..
中 User _host1 = new Host("h1");
Host _host2 = new Host("h2");
System.out.println(_host1); //class Host Name: h1
System.out.println(_host2); //class Host Name: h2
_host1.test(); //this gives me an error
_host2.test(); //this is fine
我确信_host1
和_host2
都属于Host
类。
我不明白为什么通过动态绑定创建的_host1
无法访问类test()
中的方法Host
我在这里缺少什么?
答案 0 :(得分:0)
如果它被声明为User
,则您只能使用User
方法 - 即使它实际上是Host
类型。