Casting Subclasses, Base classes
I am a VB6 programmer learning VB.Net and am having trouble with the following concept.
I have two classes
Base class: Person
Subclass: Employee
Dim obj As Person = New Employee()
In simple terms, what is happening in memory (stack, heap)
When I try to do this:
Dim obj As Employee = New Person()
I get a cast error at runtime.
Why is that?
Is it illegal to cast from a subclass to a base class?
Re: Casting Subclasses, Base classes
Do you have Option Strict turned On?
Re: Casting Subclasses, Base classes
Consider these two classes:
vb.net Code:
Public Class Person
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
End Class
Public Class Employee
Inherits Person
Private _payrollNumber As Integer
Public Property PayrollNumber() As Integer
Get
Return _payrollNumber
End Get
Set(ByVal value As Integer)
_payrollNumber = value
End Set
End Property
End Class
Now look at this code:
vb.net Code:
Dim p As Person = New Employee
p.Name = "John Citizen"
That code makes sense, right? You create a new Employee object and Employee inherits Person so you know that that object is a Person so you can assign it to a Person variable and access the Name property.
Now look at this code:
vb.net Code:
Dim e As Employee = New Person
e.PayrollNumber = 1
This code doesn't make sense, right? You're creating a Person object, which only has a Name property, and trying to assign it to a variable of type Employee. If you have an Employee variable you would expect to be able to access its PayrollNumber property, right? This object doesn't have a PayrollNumber property though, because it's NOT an Employee, therefore it cannot be assigned to an Employee variable.
Think about it. This is not a programming concept specifically. OOP is based on real-world objects and they behave exactly the same way. Every Cat is an Animal, but not every Animal is a Cat. Wherever you are allowed to take an Animal, you are allowed to take a Cat because a Cat is an Animal. Take a Cat to a vet and they'll treat it, right? The converse is not true though. Places that expect a Cat will not accept just any Animal. Try entering an Elephant into a Cat show and you'll see what I mean. ;)
Re: Casting Subclasses, Base classes
That makes a lot of sense when you put it in real world terms.
I hope the rest of the language turns out to be that logical.
Thank You so much!!!
Re: Casting Subclasses, Base classes
Quote:
Originally Posted by
rericac
I hope the rest of the language turns out to be that logical.
It pretty much does, although it's not always immediately obvious what the real-world analogue is. Interfaces is a great example. They can confuse at first but when you understand how they relate to real-world objects their purpose becomes much clearer. Maybe we'll see you back when you get up to learning about them. :)