Krowi
Krowi

Reputation: 1615

Property from base class may not be public in child class

I have a child class that inherits from a parent class. This parent class has a property Id. In my child class I want to give that the property Id and change the parents Id property to a different name in my child class.

Public Class Product ' This is the base class
    Private _iId As Integer
    Public ReadOnly Property Id As Integer ' This is the Id from the product
        Get
            Return _iId
        End Get
    End Property
End Class

Public Class OrderProduct ' This is the child class
    Inherits Product

    Private _iId As Integer
    Public ReadOnly Property Id As Integer ' This has to be the Id of the Order
        Get
            Return _iId
        End Get
    End Property

    Private _iIdProduct As Integer
    Public ReadOnly Property IdProduct As Integer ' This has to be the Id of the Product
        Get
            Return ? ? ?
        End Get
    End Property
End Class

Upvotes: 1

Views: 102

Answers (1)

Sam Axe
Sam Axe

Reputation: 33738

Public Class Product
  Protected iID As Int32 = -1
  Public Readonly Property ID As Int32
    Get
      Return iID
    End Get
  End Property
End Class


Public Class OrderProduct
  Inherits Product

  Protected  iID As Int32 = -1
  Public Shadows Readonly Property ID As Int32
    Get
      Return iID
    End Get
  End Property

  Public Readonly Property ProductID As Int32
    Get
      Return MyBase.ID
    End Get
  End Property
End Class

This is a really bad idea. This would be a definite abuse of inheritance. Rather consider encapsulation, where your OrderProduct has a property for both the Product and the Order. Or make your Order class contain both a ProductID and an OrderID.

Redefining the ID in your derived class is a really bad idea.

Upvotes: 1

Related Questions