0

I have subclass Host that extends superclass 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");
    }
}

inside 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

I am sure both _host1 and _host2 is of class Host .

What I dont understand is why _host1 which is created through dynamic binding cannot access the method test() inside class Host

What am I missing here?

Sasino
  • 69
  • 2
  • 8

1 Answers1

0

If it's declared as a User then you can only use User methods on it - even if it is actually of type Host.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213