I'm not sure which title to give to this question so if You have any idea I'll modify it right away. Anyway my question is simple:
I have a class "User" and a class "Student" that extends User; when I create the object using User u = new Student()
, is there a way to access the methods from the "Student" class even if I decalred it as a "User"? I have a "login()" method inside my student class but when I try to call it with u.login()
it tells me that there is no method login for the object User. Does that mean that to use my Student class methods I have to declare it as Student s = new Student()
? I hope my question is clear. Thank you all.
CodePudding user response:
Even though you have a Student object type, your reference is of type User. You will only have access to methods/fields (that are not private) of your User reference.
Think of this remote - tv analogy: you have a tv with multiple functions, like browsing tv channels, youtube, netflix. However, your remote can only browse tv channels, so you will not have access to youtube and netflix. Getting a new remote would work.
What works:
Student s = new Student()
;- moving the
login()
method inside User. You may also want to override this method inside your Student class to include Student capabilities. Then you can callu.login()
and the overridden version of the method would be invoked even though the object reference has User type (further info); - casting the reference type from User to Student:
((Student) u).login()
(further info).
CodePudding user response:
A parent class does not have knowledge of child classes.
Here, User u = new Student()
u is of reference type User
which can't invoke child method login()
.
class User {
public String name;
public User(String name)
{ System.out.println("Constructing User object");
this.name = name;
}
public String getName()
{
return this.name;
}
}
class Student extends User {
public String studentName;
public Student( String studentName)
{
super(studentName);
System.out.println("Constructing Student object");
this.studentName = studentName;
}
public void login()
{
System.out.println("login method");
}
}
public class Test {
public static void main(String args[])
{
User u = new Student("testname");
u.login(); //compilation error []
Student s = new Student("testname1");
s.getName(); //child can call parent class method.
}
}