Can you assign an object of derived class to the variable of base class and if both have the same method name then which will be invoked?
Yes, you can assign an object of a derived class to a variable of the base class type. This is a common feature in object-oriented programming and is known as polymorphism. When you have a method with the same name in both the base and derived classes, the version of the method that will be invoked depends on the actual type of the object, not the type of the variable it's assigned to.
if both classes have the same method names then method of the base class will be invoked. Let's illustrate this with an example in C#:.
public class BaseClass
{
public void CallMe()
{
Console.WriteLine("Base class method invoked.");
}
}
public class ChildClass : BaseClass
{
public void CallMe()
{
Console.WriteLine("Child class method invoked.");
}
}
Now we create an instance of the child class and assign it to the base class:
BaseClass obj = new ChildClass();
obj.CallMe();
Output: