Search code examples
javaupcasting

Does up casting in Java hide the subclass methods and fields?


On the program I'm writing I have a class RestrictedUser and class User that is derived from RestrictedUser. I'm trying to hide the User specific methods by casting to RestrictedUser but when I do the casting the User methods are still available. Also when I run the debugger the type of the variable comes up as User.

RestrictedUser restricted = regularUser;

Does up casting in Java hide the subclass methods and fields or am I doing something wrong? Is there a workaround?

Thanks


Solution

  • If you were to attempt to run this code:

    User user = new User(...);
    RestrictedUser restricted = user;
    restricted.methodDefinedInTheUserClass(); // <--
    

    you would get a compilation error. That won't be secure in any way, shape, or form, because even if you were to pass around the RestrictedUser to, say, another method, that method could do this:

    if (restricted instanceof User) {
        User realUser = (User)restricted;
        realUser.methodDefinedInTheUserClass(); // !!
    }
    

    and your "restricted" user isn't so restricted anymore.

    The object is showing up in the debugger as a User object because it is as User object, even if the object reference is stored in a RestrictedUser variable. Basically, putting an instance of a child class in a variable with a parent class's type will indeed "hide" the subclass's methods and fields, but not securely.