Ralph Maurmeier Ralph Maurmeier - 12 days ago 5
Vb.net Question

Inheritance confusion vb.net

I searched over 20 articles and I am still slightly confused with inheritance. I have three classes as such:

Class A

Private _Mode As String

Public Function returnMode() As String
Return _Mode
End Function

Class B
Inherits Class A

Private _Mode As String = "modeb"

Class C
Inherits Class A

Private _Mode As String = "modec"


Now any time I create a B or C class, I would like the object to return the child class _Mode. I can make the New() function _Mode = "modeb" but I wanted to know a better way or more correct way.

How do I properly declare the variable _Mode?

Answer

One option would be to make _Mode Protected instead of Private so you can set it from the subclasses, and set the value is the subclass constructors:

Class A

    Protected _Mode As String

    Public Function returnMode() As String
        Return _Mode
    End Function

Class B
    Inherits Class A

    Public Sub New()
        _Mode = "modeb"
    End Sub

Class C
    Inherits Class A

    Public Sub New()
        _Mode = "modec"
    End Sub