

If you are sure that the object is of ChildClass Type, you can typecast baseObject to "ChildClass" and then use the ChildClass members Hence you can only see the objects of "BaseClass" type. The static declared type of the object is that of " BaseClass". When you do BaseClass baseObject= new ChildClass() It explains it in the simplest way possible, without tying it down to any particular programming framework, which in my opinion is the best way to learn OO.

Have a look at this excellent StackOverflow question: Try to describe polymorphism as easy as you can This type of concept (polymorphism) is fundamental to Object-Orientated programming. Int x = ((ChildClass)b).z // works - this is a cast, throws exception in bad conversionĬhildClass c = b as ChildClass // also works, different type of cast, returns null in bad conversion In order to access the child properties, you need to cast it as the child type: BaseClass b = new ChildClass() You can't see the child properties because you have said "baseObject" is of type "BaseClass" - the compiler has typed the object to this. This technique ties in closely with the user of interfaces.Į.g public BaseClass GetDynamicChildClass()Įlse if (someOtherCondition) return SomeOtherChildClass() But if you specified the return type of "BaseClass", you could return all the 10 types of child classes from the one method. What if you wanted a method to return each type of child class? Well, without this type of declaration you would need 10 methods.
SCENARIO BASED OOPS INTERVIEW QUESTIONS CODE
Developers do this to provide abstraction over what actual object they are referring to, which provides flexibility and 'loose-coupling' over the code that uses it.įor example (common scenario - which i use a lot), you might have 10 child classes which extend the base class.
