I have a question related to OOPS concept.
I have a base class
public class BaseClass
{
public int i = 10;
public int x = 30;
public string str = "Hello";
public virtual string Hello()
{
return "Hello of base class called";
}
}
I have a child class
public class ChildClass : BaseClass
{
public int i = 20;
public int z = 90;
public override string Hello()
{
return "Hello of child class called";
}
}
Now i have seen that the below code works fine
BaseClass baseObject = new ChildClass();
and when I type baseObject. then i only see members of BaseClass only.
First question: Can someone advise me on a situation where a developer needs to do this BaseClass baseObject = new ChildClass();?
Second question: If my BaseClass object has a reference to my child class object then why are my child member variables not accessible through this baseObject?
To answer your first question.
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.
For example (common scenario – which i use a lot), you might have 10 child classes which extend the base class. What if you wanted a method to return each type of child class? Well, without this type of declaration you would need 10 methods. But if you specified the return type of “BaseClass”, you could return all the 10 types of child classes from the one method. This technique ties in closely with the user of interfaces.
E.g
To answer your second question.
You can’t see the child properties because you have said “baseObject” is of type “BaseClass” – the compiler has typed the object to this. In order to access the child properties, you need to cast it as the child type:
This type of concept (polymorphism) is fundamental to Object-Orientated programming. Have a look at this excellent StackOverflow question: Try to describe polymorphism as easy as you can
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.
Hope that helps.