Link to home
Start Free TrialLog in
Avatar of glenn_r
glenn_r

asked on

inheritance and overloading class methods in the subclass

Is it possible to declare a method in a class as overloadable and then overload it in a subclass?
Is there a 'mustoverride' equivalent for 'mustloverload' to force an implementation in a subclass?

example

Public MustInherit Class Beverage2

    Public description As String

    Overridable Function getDescription() As String
        Return description
    End Function

End Class

Public Class Pepsi
    Inherits Beverage2

    Sub New()
        description = "pepsi"
    End Sub

    Public Shadows Function getDescription(v As String) As String
        Return description & " "
    End Function

End Class
Avatar of it_saige
it_saige
Flag of United States of America image

Did you mean something like this -
Public MustInherit Class Beverage
	Public MustOverride Property Description() As String

	Public Overridable Shadows Function ToString() As String
		Return Description
	End Function
End Class

Public Class Pepsi : Inherits Beverage
	Private _description As String
	Public Overrides Property Description() As String
		Get
			Return _description
		End Get
		Set(ByVal value As String)
			If Not value.Equals(_description) Then
				_description = value
			End If
		End Set
	End Property

	Public Sub New(ByVal Description As String)
		_description = Description
	End Sub

	Public Overrides Function ToString() As String
		Return MyBase.ToString()
	End Function
End Class

Module Module1
	Sub Main(ByVal args As String())
		Dim drink As Pepsi = New Pepsi("Cool refreshing cola")
		Console.WriteLine(drink.ToString())
		Console.ReadLine()
	End Sub
End Module

Open in new window

Produces the following output:User generated image
-saige-
Avatar of glenn_r
glenn_r

ASKER

i want to do what you've illustrated but with overloading a method
Is it possible to overload a method of a derived class?
ASKER CERTIFIED SOLUTION
Avatar of ChloesDad
ChloesDad
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of glenn_r

ASKER

got it
in all my years doing this i never thought about that one
thanks again
i need to find a pepsi in a vintage glass bottle those are the best!!
As ChloesDad stated, there is no way to force overloading of a method.  The reason for this is because overloading is optional and overloading a method basically says to the compiler, "I am defining a method that my parent contains.  I may choose to use the parent method or just provide a different set of instructions alltogether."

-saige-