Overridable Scope

H

H

Here is a good one!!

A book I am reading on OOP states

'If any method is marked to allow overriding, the access can be changed by a
derived class.'

Also

'A derived class can even change a method's scope to public or private if
it's allowed to overide the method.'

However, if I write this code:

Public MustInherit Class Product
Protected Price As Double = 1
Protected Shipping As Double = 2

Protected Overridable Function CalculatePrice() As Double
CalculatePrice = Price + Shipping
End Function

End Class

Public Class LargeProduct
Inherits Product

Protected ShippingSurcharge As Double = 5

Public Overrides Function CalculatePrice() As Double
CalculatePrice = MyBase.CalculatePrice + ShippingSurcharge
End Function

Public Sub New()
MyBase.New()
End Sub

End Class

I get the error message:

Public Overrides Function CalculatePrice() As Double' cannot override
'Protected Overridable Function CalculatePrice() As Double' because they
have different access levels.

Have I done something wrong or is the book wrong?

Thanks
 
G

Guest

As you've learned from your experiment, the book is wrong. You must retain
the same access level when overriding a method, with one exception (which is
noted below).

From the Visual Basic.NET specification (Section 9.2.3):

A method may not override another method if the overriding method's
accessibility domain is not equal to the accessibility domain of the method
being overridden. The one exception is that a method overriding a Protected
Friend method in another assembly must specify Protected (not Protected
Friend).
 
H

H

Thanks

I have read in several book reviews that sams publishing has a tendency to
print inacurate information.

H
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top