In my interview on a IT Services & Consulting Company, the interviewer has asked about the following situation of inheritence. At first i couldn’t recollect it. But after coming back in my home, i have tried it out.

 The scenario was there are two interfaces IWheel and IMeters with same method signature declared inside it, “Display()”. One class is implementing this two interfaces, would that be possible? and How you can implement both of the methods?

It’s possible, with the following code. Go through the sample code and leave comments if any suggestions.

[code lang=”c-sharp”]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApp02
{
class Program
{
static void Main(string[] args)
{

TestInheritence objInherit = new TestInheritence();

// objInherit.Display() — Not valid since, two interface method implementations of the same name and signature.
// So compiler can’t identify this method.
// These methods are implemented for each interface specific.
// You have to implicitly initialize objects of the TestInheritence class to hold it in
// Correponding interfaces.

IWheel myWheel = new TestInheritence();

IMeter myMeter = new TestInheritence();

//Calls the implementation method of IWheel.Display() method.
myWheel.Display();

//Calls the implementation method of IMeters.Display() method.
myMeter.Display();

Console.Read();

}

public class TestInheritence : IWheel, IMeter
{
#region IWheel Members

void IWheel.Display()
{
// throw new NotImplementedException();
Console.WriteLine("** IWheel.Display() **");
}

#endregion

#region IMeter Members

void IMeter.Display()
{
//throw new NotImplementedException();
Console.WriteLine("** IMeter.Display() **");
}

#endregion
}

public interface IWheel
{
void Display();
}

public interface IMeter
{
void Display();
}

}
}

[/code]

Result Ouput is

images

I too was confused a bit. So mentioned some unsure answers. But i got the answer after i reach home. So thought i should share this for others, so that would be useful for them in future.  I am attending interviews after long 3 and half years, so need to improve a lot. Trying and trying we will get in right, that’s what i am doing now. Kool. It improves my knowledge lot, and i do have patience, so day i will get through. Each interview refreshes  new, new valuable information. Cool…

Kudos!!!!!


Discover more from Cloud Distilled ~ Nithin Mohan

Subscribe to get the latest posts sent to your email.

By Nithin Mohan TK

Technology Enthusiast | .NET Specialist | Blogger | Gadget & Hardware Geek

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.