Variable declaration & object creation

DanielWuVB

New member
Joined
Jun 7, 2007
Messages
3
Programming Experience
Beginner
Hi ! I'm new and self studying VB.NET. can someone explain to me if I have a parent class -Person and subclass employee. why should I coded as follow(from a book)

Dim objPerson as Person = New Employee

why not just do

Dim objPerson as Employee = New Employee

since Class Employee is subclass of Person. what's good for that ?
Thanks
Daniel
 
You shouldn't, unless you specifically need a Person variable. There's nothing to stop you doing that but there's no reason to do it unless you need to be able to assign other objects to that same variable that are not Employee objects. If you use the first line of code then you can't access any Employee-specific members via that variable, only those inherited from the Person class.

Also, the .NET terminology is "base class" and "derived class".
 
Thank you very much

Thanks ! I think why the book coded this way is just want to demonstrate the example ~ maybe
Thanks you very much....
Daniel
 
Another Question ...

if I don't need to assign another object to the same variable. can I say Variable type normally will same like data type ???

Dim objEmployee as Employee = New Employee
 
Absolutely. Unless you have a reason to declare the variable as some other type you have no reason to declare the variable as some other type. That may seem like circular logic but what I'm saying is that if you declare the variable as some other type then you are going to deny access to some of the object's members. Why would you do that without a compelling reason?
 
Back
Top