If I have a class called A and a class called B, if B inherits A that means A is the super class and B is the subclass. I have been asked to describe why class A is not an abstract class but as i see it class A is an abstract class A, as it has been created for Class B to use in the future, is it something to do with Class B not being able to access the fields in Class A as although they are private by default?
Class A looks something like this
Public Class A
StartDate As Date
Men As Integer
Place As String
Public Sub New()
StartDate = Today
Men = 0
Place = ""
End Sub
End Class
Class B Looks like this
Public Class B inherits Class A
Grade As ExamGrade
Public Sub New()
MyBase.New
StartDate = Today
Men = 0
Place = ""
Grade = 'Easy'
End Sub
Public Function setGrade(grade As String)
ExamGrade = grade
End Function
End Class
In order to be abstract, class A must have the MustInherit
keyword.
Abstract (MustInherit
) means that this class serves as base class only and cannot be instantiated with New
. It also allows you to declare abstract (MustOverride
) members with no implementation, i.e. no method body. The inheriting classes then must override the abstract members and provide an implementation unless they are abstract themselves (where a third level of deriving classes would then provide an implementation).
Note that you are allowed to call an abstract member. At runtime the implementation of the actual implementing class will be called.
See: MustInherit (Visual Basic)
Members are private if not specified otherwise. Specify them to be Protected
to allow descendant classes to see them or Public
to allow "everybody" to see them.
See: Access Levels in Visual Basic
Public MustInherit ClassA
Protected StartDate As Date
Protected Men As Integer
Protected Place As String
Public Sub New()
StartDate = Today
Men = 0
Place = ""
End Sub
Public MustOverride Sub Print()
End Class
Public ClassB
Inherits ClassA
Public Grade As String
Public Sub New()
MyBase.New() 'This initializes StartDate, Men and Place
Grade = "Easy"
End Sub
Public Sub SetGrade(ByVal grade As String)
Me.Grade = grade
End Sub
Public Overrides Sub Print()
Console.WriteLine($"Grade = {Grade}")
End Sub
End Class
Now, you can use it like this
Sub Test(ByVal a As ClassA)
a.Print()
End Sub
You can call Test
by passing it a ClassB
object.