Wednesday, December 07, 2011

Inheritance and Type Casting

When a derived class is inherited from a base Class, objects of derived class can be assigned to variable of base class.

[CS]

Employee emp= new Employee();

Person per= emp;

 

[VB]

Dim emp as new Employee()

Dim per as Person = emp

When derived class object is assigned to base class variable, we can only access base class members through that variable. But we can access derived class members through derived class variables or type casting the base class back to derived class.

[CS]

per.Name = “Muthukrishnan”;

emp.Department = “Technical”;

(per as Employee).DOJ = datJoiningDate;

 

[VB]

per.Name = “Muthukrishnan”

emp.Department = “Technical”

CType(per,Employee).DOJ = datJoiningDate

Here type casting is only possible because the “per” base class variable holds derived class object.

Base class objects can not be type casted to derived class variables.

For example

[CS]

Person per = new Person();

Employee emp = per;

 

[VB]

Dim per as new Person()

Dim emp as Employee = per

Above code will through error during compile time.

We can force the type casting so that the code can be compiled.

[CS]

Person per = new Person();

Employee emp = (per as Employee);

 

[VB]

Dim per as new Person()

Dim emp as Employee = CType(per, Employee)

But above code will throw error during runtime.

No comments:

Post a Comment