Search code examples
vb.netinheritancecomposition

Composition and inheritance in VB.Net


So here is the case. I have class A and B. Class A has a member in it which is Class B

Public Class A
    public _lstB as list (of B)
    public sub new()
        _lstB = B.Init()
    end sub
end Class

Public Class B
    public shared sub Init() as list (of B)
        ....
    end sub
End Class

No what I want to do is create a derived class for A and B (lets say DA and DB). I would like the member B to be replace with DB in DA. Is this possible?

Public Class DA
    inherits A
    public _lstDB as list (of DB)

    public sub new()
        mybase.new 
        _lstDB = DB.Init()
    end sub
end Class

Public Class DB
    inherits B
    public shadows shared sub Init() as list (of DB)
        ....
    end sub
End Class

I'm entirely sure this is the way to go, because in the call to

mybase.new 

An entire list (of B) is going to be created in the base class that will never endup being used!


Solution

  • You are always free to put whatever members you want in base classes and derived classes; there's nothing stopping you from doing that. How you want to use those classes is up to you. If you need a collection of B instances in your A class, then that's fine, or if you need a collection of DB classes in DA, that's fine too.

    You could also code it up so that when you're adding an instance of DB to the collection you have in the DA class, you add that instance to the base class' (A) collection which is OK because DB derives from B. For instance, if you have this method in A:

    Public Overridable Sub AddNew(item As B)
        _lstB.Add(item)
    End Sub
    

    and this method in DA:

    Public Overrides Sub AddNew(item As B)
        MyBase.AddNew(item)
    End Sub
    

    Then you are only ever storing one collection, in the base class A.

    It all depends on how you want to use your class -- what your specific needs are for your design.