I have just learnt inheritance and polymorphism, in C#, and I am confused between these 3 cases. You can create an instance when we have a base and derived class.
Could you please explain the differences (Especially Obj1 with Obj2)?
class Program
{
static void Main()
{
Shape obj1 = new Shape();
Shape obj2 = new Rectangle();
Rectangle obj3 = new Rectangle();
}
}
class Shape
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
class Rectangle : Shape
{
public string Property3 { get; set; }
}
CodePudding user response:
Shape obj1 = new Shape();
obj1 is a shape. It has Property1 and Property2. It doesn't have a Property3.
Shape obj2 = new Rectangle();
obj2 is a Rectangle
that was downcast to a Shape
the moment you instantiated it. If Rectangle
overrides any Shape
behaviours (which it doesn't in your example) then the Rectangle
behaviours will be called at runtime, rather than the behaviours of the base Shape
class. It has a Property3
that it could use in its internals, but you can't access it from this method because it's already down-cast to a Shape
.
Rectangle obj3 = new Rectangle();
obj3 is Rectangle
. You can access Property3
from this method. You can pass it to any method that requires a Shape because a Rectangle
is a Shape
.
I recommend that you write some more code along these lines and debug it in a simple console app to see what happens in different circumstances. Personally, I find that learning by doing is the best way.