0

I have tried to implement the Factory method with a trick, but for some reason is not working:

Public Class MetamodelElement
Public Class MetamodelElementFactoryBase
End Class

Private Sub New()
End Sub

End Class

Public Class MetamodelElementFactory : Inherits MetamodelElement.MetamodelElementFactoryBase
    Function CreateMetamodelElement() As MetamodelElement
        Return New MetamodelElement()
    End Function

End Class

It says that the class does not have access to the private method (constructor).

I have followed an example from C# in this post: Hidden Features of C#?

Community
  • 1
  • 1
user4388177
  • 2,433
  • 3
  • 16
  • 30
  • _"but for some reason"_ any chance that you tell us the compiler error? – Tim Schmelter Feb 27 '15 at 13:43
  • You're right, I should have been more precise. I have edited the question. – user4388177 Feb 27 '15 at 13:46
  • 'Inner class Factory Method' => you need to move Public Class MetamodelElementFactory inside Public Class MetamodelElement – tolanj Feb 27 '15 at 13:49
  • or add a Protected method CreateMetamodelElement()in Public Class MetamodelElementFactoryBase and call _that_ from MetamodelElementFactory, Which is the paradigm being shown in th linked c# example – tolanj Feb 27 '15 at 13:51

1 Answers1

1

The compiler complains that you are trying to use the Private constructor from outside of the class. That is not allowed. So either make it Public or don't call it.

Public Class MetamodelElement
    Public Class MetamodelElementFactoryBase
    End Class

    Public Sub New()  ' <---- HERE!!! Now it works because it's public
    End Sub

End Class

Public Class MetamodelElementFactory
    Inherits MetamodelElement.MetamodelElementFactoryBase

    Function CreateMetamodelElement() As MetamodelElement
        Return New MetamodelElement() ' <--- HERE was the error
    End Function

End Class

You can access private class members only from inside of the class.

MSDN: Access Levels


According to the C# code that you've linked you have to move the constructor into the class that you are inheriting from. Then you can also use Protected:

Public Class MetamodelElement
    Public Class MetamodelElementFactoryBase
        Protected Sub New()
        End Sub
    End Class
End Class
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939