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
If you were to attempt to run this code:
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
RestrictedUserto, say, another method, that method could do this:and your ‘restricted’ user isn’t so restricted anymore.
The object is showing up in the debugger as a
Userobject because it is asUserobject, even if the object reference is stored in aRestrictedUservariable. 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.