Question

Given the following code:

interface IParent
{
    void ParentPrintMethod();
}

interface IChild : IParent
{ 
    void ChildPrintMethod();
}

class Baby : IChild
{
    public void ParentPrintMethod()
    {
       Console.WriteLine("Parent Print Method");
    }

    public void ChildPrintMethod()
    {
       Console.WriteLine("Child Print Method");
    }

}

All is well at this point. If you were to create a new instance of the Baby class as follows,

Baby x = new Baby();

everything is ok, and you would have access to the ParentPrintMethod() and the ChildPrintMethod();

However, can somebody please explain to me what would happen if you were to do the following?

IParent x = new Baby();

Would you have access to the ChildPrintMethod() in this case? What exactly is happening when you do this?

Was it helpful?

Solution

Then you're specifying you're interested only in the Interface declared by Parent so you would only have access to those methods declared in Parent even if the instance of the object itself has more available.

OTHER TIPS

No, you would not. The variable x, as type Parent (by the by, interfaces are idiomatically named with an I at the beginning) would only see the methods defined in the Parent interface. Period.

Your reference to the object will behave like an instance of the Parent interface and will not have access to the Child methods.

This sounds really abnormal but: All Children are Parents, but not all Parents are Children.

It doesn't make sense for a Parent to access a Childs methods because it would be an error in the case that the parent isn't a child.

It is still possible to access the child methods in your example given, but you must cast x to a Child first, ((Child)x).ChildPrintMethod(). This is sound because in the event that x is not a valid Child, an exception is thrown when the cast happens, rather than attempting to run the method.

You can test ahead whether this should work, rather than having to catch exceptions by using if (x is Child)

Edit:

To reuse the variable as if it were a child, you can create a local reference to it like this:

if (x is Child) {
    Child y = (Child)x;
    ...
}

There is no such thing as "inheritance skipped". Your object is just viewed 'through' one of its interfaces, effectively hiding anything else not declared in that interface. There's no magic in it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top