Home > database >  How to narrow cast parent class to child class
How to narrow cast parent class to child class

Time:12-20

I am creating a University Management system where I have a Database class where I store the currentUser object of class User. Upon a successful login currentUser object becomes a Student or a Teacher object (which are User's children). But when I try to call Student's method on the currentUser object it doesn't work.

here is the object currentUser: public static User currentUser; so the currentUser is not initialized and I don't want to downCast it at this stage,

this is how I authorize a user: `

if(student.getLogin().equals(login) && student.getPassword().equals(password)) {
                    currentUser = student;
                    isLogedIn = true;
                }

`

I tried type casting User to Student like this: `

currentUser = student;
                    currentUser = (Student) currentUser;

` but I still can't call Student methods on currentUser. How can I fix it?

CodePudding user response:

currentUser is a variable of type User, so you can only use its (and its parents') method through it.

You could cast the actual instance to a Student and store it in a temporary variable of that type to use Student's methods:

Student currentStudent = (Student) currentUser;
currentStudent.someStudentMethod();

Of course, you can also omit the storing and call the method directly on the cast instance:

((Student) currentUser).someStudentMethod();
  • Related