ISCL is a Intelligent Information Consulting System. Based on our knowledgebase, using AI tools such as CHATGPT, Customers could customize the information according to their needs, So as to achieve

MustInherit and NotInheritable in VB.NET

1
< Continued from page 2

On the previous pages, the 'how' and 'why' of both MustInherit and NotInheritable were explained. In the application "WorkInAmerica" below, an example of both are combined in a single program. Here's the code:

Public Structure WorkHours    Dim IWorked As Decimal    Dim myBossWorked As Decimal End Structure Public Class WorkInAmerica    Private Sub ADaysWork_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles ADaysWork.Click       Dim myJob As New Worker       Dim myBoss As New Boss       Dim theHours As New WorkHours       theHours.IWorked = 0       theHours.myBossWorked = 0       ' The workday ....       myJob.doWork(8, theHours)       myBoss.doWork(8, theHours)       Console.WriteLine("I worked: " & _          theHours.IWorked)       Console.WriteLine("My boss worked: " & _          theHours.myBossWorked)    End Sub End Class Public MustInherit Class Employee    MustOverride Sub doWork( _       ByVal hours As Decimal, _       ByRef theHours As WorkHours) End Class Public NotInheritable Class Worker    Inherits Employee    Public Overrides Sub doWork( _       ByVal hours As Decimal, _       ByRef thehours As WorkHours)       thehours.IWorked += hours    End Sub End Class Public NotInheritable Class Boss    Inherits Employee    Public Overrides Sub doWork( _       ByVal hours As Decimal, _       ByRef thehours As WorkHours)       thehours.myBossWorked += (hours / 2)       thehours.IWorked += (hours / 2)    End Sub End Class


Both the worker and the boss have assigned workdays of eight hours:

myJob.doWork(8, theHours) myBoss.doWork(8, theHours)
But the output is:

I worked: 12 My boss worked: 4
The class Employee is marked MustInherit and the doWork method is marked MustOverride so both the Boss class and the Worker class are required to have their own separate doWork procedures. The Boss class only does half the work and then adds the hours not worked to the Worker's hours. Finally, Boss class and the Worker class are both marked NotInheritable so no one can create a new class and change the way things work.
Source...
Subscribe to our newsletter
Sign up here to get the latest news, updates and special offers delivered directly to your inbox.
You can unsubscribe at any time

Leave A Reply

Your email address will not be published.