< Day Day Up > |
An important thing to keep in mind about inheritance and accessibility is that a derived class does not have access to its base classes' Private members. Private members can be accessed only by the immediate type in which they're defined. Protected members, however, can be accessed within an inheritance hierarchy. The Protected access level restricts access to a member to only the class itself, but it extends access to all derived classes as well. For example: Class User Private SSN As String Protected Password As String End Class Class Guest Inherits User Sub New() ' Error: SSN is private to User SSN = "123-45-7890" ' OK: Password is protected and can be accessed Password = "password" End Sub End Class The class Guest can access the Password field inherited from its base class because it is Protected . However, it cannot access the SSN field, because it is Private . When a class accesses a Protected member, the access must take place through an instance of that class or a more derived class. It cannot take place through a base class. For example, the following code is incorrect. Class User Protected Name As String Private SSN As String Protected Password As String End Class Class Guest Inherits User Shared Sub ChangeName(ByVal u As User, ByVal Name As String) ' Error: Access to Name in User cannot go through ' base class User u.Name = Name End Sub End Class This rule may seem strange , but it is necessary to prevent unexpected access to Protected members. Without the rule, it would be possible to gain access to a Protected member of another type simply by deriving from a common base class. Class User Protected Name As String Private SSN As String Protected Password As String End Class Class Administrator Inherits User End Class Class Guest Inherits User Public Sub PrintAdministratorPassword(ByVal u As User) ' Error: Access to Password in User cannot go through ' base class User Console.WriteLine(u.Password) End Sub End Class In this example, Guest cannot access Administrator 's protected field Password ”it can only access the Password field of instances of Guest .
|
< Day Day Up > |