Saturday, May 22, 2010

Which of the following may result in a compiler error in C#?

1) Referring to a derived class object with a base class reference





2) Referring to a base class object with a derived class reference





3) Referring to a base class object with a base class reference





4) Referring to a derived-class object with a derived class reference








Sorry, but I don't understand this at all. It's really confusing. Can you explain it to me, please?

Which of the following may result in a compiler error in C#?
#2 will be an error.





Imagine you have a superclass called GeometricFigure, and two subclasses called Circle and Square.





Create one object of each type.





Then, since the Circle object IS A GeometricFigure object (it's a subclass), then it's ok to have a reference of type GeometricFigure that refers to the Circle. That's the whole point of inheritance.





However...it's not true that a GeometricFigure IS A Circle. It might be or it might not be. But if it WASN'T a Circle (maybe it was a Square), and you tried to call its circumference() function...big problem.





So as a rule, for any given object, you can use a reference to its actual class or any of its PARENT classes or interfaces. You can't use a reference for any of its subclasses.





(#3 and #4 are obviously ok to do.)

bloom

No comments:

Post a Comment