Sunday, May 11, 2008

Implementing Two interface having the same method signature in the same class

There can be scenario when we would have two interface with the same method name and same type of arguments, same number of arguments and even the return type can be same and we need to implement both the interface in the same class. How to implement the interface in our class? Most of you will be thinking whats so tough in this, just implement the interface and the method and move on. If the signature of the methods in the interface were different then there would have been no problem but here the signature of the methods in two different interface are same and both the interfaces are gonna be implemented in the same class. The two interface are as below.
public interface IA
{
string PrintName();
}
public interface IB
{
string PrintName();
}

From the above code we can infer that we have two interface with names IA and IB and both have a single method named “PrintName”. The signature of both the methods are same and we need to implement the interfaces in our class say “A”. One way of impelementing the interface is as shown below i.e. just having a “public” implementation of the interface method only once.
public class A : IA, IB
{
public A()
{
}
public string PrintName()
{
return this.GetType().Name;
}
}

The above implementation has got a limitation i.e the method “PrintName” is considered to be a common method for all i.e commong method for the class, and for the interfaces IA and IB. If you are writing a code shown below
A a = new A();
IA ia = new A();
IB ib = new A();
Console.WriteLine(a.PrintName());
Console.WriteLine(ia.PrintName());
Console.WriteLine(ib.PrintName());

all the calls to method “PrintName” will give you the same result, the name of the class i.e. “A”. This is because all call to the method goes to the same definition. Now if you want to give different implementation to the methods in interface IA and IB, what will you do? Its also simple, just have two impelementation of the same method and prefix the method names with the interface name as shown below.
public class A : IA, IB
{
public A()
{
}
string IA.PrintName()
{
return “IA PrintName Method”;
}
string IB.PrintName()
{
return “IB PrintName Method”;
}
}

Now the below code will give you different output.
IA ia = new A();
IB ib = new A();
Console.WriteLine(ia.PrintName());
// Will print "IA PrintName Method"
Console.WriteLine(ib.PrintName());// Will print "IB PrintName Method"
So this is how two interfaces having the same method signature can be given different implementation in the same class.

117 comments:

  1. Thank you for such simple and clear solution

    ReplyDelete
  2. Nicely explained the concept.Thank You

    ReplyDelete
  3. Very simple solution.Thank u

    ReplyDelete
  4. The overall topic was good. However, it has missed out one thing.
    consider, A a = new A();

    Then there is no PrintName method for the object a.
    a.PrintName(); // Compiler Error

    ReplyDelete
  5. Hi Mukerji,
    Thanks for the comment. As you have pointed out in your comment the compiler will throw an error saying "so and so method could not be found".The reason why this was not included as a sample code was that if you are using any version of Visual Studio, which 100% of .net developers are, the intellisense will not pop the interface method as one of the methods of the class unless you cast it to the respective interface. Thanks for pointing this out and with this discussion we have closed the missing link as well. :)

    ReplyDelete
  6. very good yaar keep it up vikas.sharma2009@live.com

    ReplyDelete
  7. Thanks for this clear solution.

    ReplyDelete
  8. Excellent example...

    ReplyDelete
  9. Very nice explained...

    ReplyDelete
  10. thanks for nice example

    ReplyDelete
  11. very nice explanation

    ReplyDelete
  12. very nice explanation ....

    ReplyDelete
  13. Simple but very good explaination

    ReplyDelete
  14. Thanks guys for the positive feedback.

    ReplyDelete
  15. totally wrong ,it is not possible in .net
    ,which same method name in two interface

    ReplyDelete
  16. Hi,
    Whatever is explained in the article is very much possible in .NET. All the code pasted here have been tested thoroughly. If you could highlight the problem you are facing it will be helpful for me to help you out with your problem.

    ReplyDelete
  17. Very nice explained.Thanks

    ReplyDelete
  18. but what if in both interface I am defining same method with different return types,it will give CTE.

    interface i1{
    public void foo();
    }
    interface i2{
    public int foo();
    }

    ReplyDelete
    Replies
    1. Hi,
      If you use explicit implementation to implement the methods then there will be no issue. If you do a implicit implementation of the method, say the one having return type as void, then the compiler will not be happy. It will throw an error saying the following error
      "Error 1 'XYZClass' does not implement interface member 'i2.foo()'. 'XYZClass.foo()' cannot implement 'i2.foo()' because it does not have the matching return type of 'int'".

      Delete
  19. Hi,
    I have same scenario but in Java.
    I checked, Java compiler allows define 2 methods with same name and a class implementing both these methods(from 2 different Interfaces).
    But in the implementing class, it allows only one definition.
    Could not code as: IA.PrintName();
    So.. What's ur take on this..?? How can we implement 2 methods with same name in Java Class..?? N call them explicitly..??

    ReplyDelete
  20. I am not a Java expert. But whatever little bit of googling I did I came to know that Java doesn't support prefixing a method name with an interface name. Below is a link which talks about the problem.

    ReplyDelete
  21. You can use two types of techniques

    1. Implicit Implementation Technique
    2. Explicit Implementation Technique

    .Net Training In Chennai

    ReplyDelete
  22. I didnt understand how interface is instantiated here. Interface can not be instantiated.

    ReplyDelete
    Replies
    1. I don't think we are talking about Interface instantiation. Can you be more specific about it?

      Delete
  23. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
    dot net training in chennai velachery | dot net training center in chennai

    ReplyDelete
  24. The blog gave me idea to Implement Two interface having the same method signature in the same class my sincere thanks for sharing this post
    Dot Net Training in Chennai

    ReplyDelete
  25. really nice blog has been shared by you before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blogs.
    dot net training in chennai

    ReplyDelete
  26. It is extremely an incredible work and the manner by which you are sharing the information is excellent.Thanks for helping me to comprehend essential ideas. As a learner in Dot Net programming your post help me a lot.Thanks for your educational article.
    Technology

    ReplyDelete
  27. I found your post while searching for some related information on blog search... Its a great blog, keep posting and update the information.
    J2EE Training in Chennai
    JAVA Training Chennai

    ReplyDelete
  28. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.


    rpa Training in Chennai

    rpa Training in bangalore

    rpa Training in pune

    blueprism Training in Chennai

    blueprism Training in bangalore

    blueprism Training in pune

    rpa online training

    ReplyDelete
  29. This is quite educational arrange. It has famous breeding about what I rarity to vouch. Colossal proverb. This trumpet is a famous tone to nab to troths. Congratulations on a career well achieved. This arrange is synchronous s informative impolite festivity to pity. I appreciated what you ok extremely here.
    Click here:
    angularjs training in rajajinagar
    Click here:
    angularjs training in marathahalli

    ReplyDelete
  30. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.

    Data Science training in marathahalli
    Data Science training in btm
    Data Science training in rajaji nagar
    Data Science training in chennai
    Data Science training in kalyan nagar
    Data Science training in electronic city
    Data Science training in USA
    Data science training in pune




    ReplyDelete
  31. hank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me 
    java training in chennai | java training in bangalore

    java online training | java training in pune

    java training in chennai | java training in bangalore

    ReplyDelete
  32. Thanks you for sharing this unique useful information content with us. Really awesome work. keep on blogging
    Devops training in velachery
    Devops training in annanagar

    ReplyDelete
  33. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    Blueprism training in annanagar

    Blueprism training in velachery

    Blueprism training in marathahalli

    ReplyDelete
  34. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.

    java training in chennai | java training in USA

    ReplyDelete
  35. Helpful information. Lucky me I discovered your web site accidentally, and I am surprised why this accident did not came about earlier! I bookmarked it.
    Click Here : caterpillar used wheel excavator

    ReplyDelete
  36. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    selenium training in chennai
    selenium training in bangalore
    selenium training in Pune
    selenium training in pune
    Selenium Online Training


    https://shrikantsonarblogs.blogspot.com/2013/07/gridview-with-viewpager-like-android.html

    ReplyDelete
  37. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete
  38. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    python Training in Pune
    python Training in Chennai
    python Training in Bangalore

    ReplyDelete
  39. Outstanding blog thanks for sharing such wonderful blog with us ,after long time came across such knowlegeble blog. keep sharing such informative blog with us.

    check out : Machine learning training in chennai
    machine learning with python course in chennai
    machine learning course in chennai
    best training insitute for machine learning

    ReplyDelete
  40. Nice post. I learned some new information. Thanks for sharing.

    karnatakapucresult
    Guest posting sites

    ReplyDelete
  41. nice course. thanks for sharing this post this post harried me a lot.
    Cloud Computing Training in Delhi

    ReplyDelete
  42. Attend The Python training in bangalore From ExcelR. Practical Python training in bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python training in bangalore.
    python training in bangalore

    ReplyDelete
  43. This comment has been removed by the author.

    ReplyDelete
  44. such a good blog. it is very informative for interface they can learn how to do digital marketing through using the different technique of: : Digital Marketing Course everyone should visit this site.

    ReplyDelete
  45. It’s really Nice and Meaningful. It’s really cool Blog. You have really helped lots of people who visit Blog and provide them Useful Information. Thanks for Sharing.Automation Anywhere Training in Bangalore

    ReplyDelete
  46. thank you for sharing this blog, it is very useful information and keep posting.....
    Java course bangalore
    javascript course bangalore

    ReplyDelete
  47. Effective blog with a lot of information. I just Shared you the link below for Courses .They really provide good level of training and Placement,I just Had ASP.NET Classes in this institute , Just Check This Link You can get it more information about the ASP.NET course.


    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  48. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    data science course in coimbatore

    ReplyDelete
  49. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

    data science training in guntur

    ReplyDelete
  50. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!

    data science training in guntur

    ReplyDelete
  51. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.

    data science training in guntur

    ReplyDelete
  52. I enjoy it for creating the details, keep up the truly amazing perform continuing
    Data Science Course in Bangalore

    ReplyDelete
  53. Superb. I really enjoyed very much with this article here. Really it is an amazing article I had ever read. I hope it will help a lot for all. Thank you so much for this amazing posts and please keep update like this excellent article.thank you for sharing such a great blog with us. expecting for your.
    Oracle Training | Online Course | Certification in chennai | Oracle Training | Online Course | Certification in bangalore | Oracle Training | Online Course | Certification in hyderabad | Oracle Training | Online Course | Certification in pune | Oracle Training | Online Course | Certification in coimbatore

    ReplyDelete

  54. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
    Ethical Hacking Course in Bangalore

    ReplyDelete
  55. Fantastic blog with very informative information, found valuable thanks for sharing
    Data Science Course in Hyderabad

    ReplyDelete
  56. This is an awesome post.Really very informative and creative contents.
    Php projects with source code

    ReplyDelete
  57. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
    Best Institute for Data Science in Hyderabad

    ReplyDelete
  58. Want to learn Oracle DBA along with the job opportunities? Infycle are with you to make your dream into reality. Infycle Technologies gives the most trustworthy Oracle DBA Training in Chennai, in 100% hands-on practical training with professional tutors in the field. Along with that, the mock interviews will be assigned for the candidates, so that, they can meet the job interviews with full confidence. To transform your career to next level, call 7502633633 to Infycle Technologies and grab a free demo to know more

    https://infycletechnologies.com/oracle-dba-training-in-chennai


    ReplyDelete
  59. Nice Blog. Thanks for Sharing this useful information...
    Great job, keep doing like this...


    Data science training in chennai
    Data science course in chennai

    ReplyDelete
  60. The methods you've indicated will be helpful.

    ReplyDelete
  61. Grab the Digital Marketing Training in Chennai from Infycle Technologies, the best software training institute, and Placement center in Chennai which is providing professional software courses such as Data Science, Artificial Intelligence, Cyber Security, Big Data, Java, Hadoop, Selenium, Android, and iOS Development, DevOps, Oracle etc with 100% hands-on practical training. Dial 7502633633 to get more info and a free demo and to grab the certification for having a peak rise in your career.

    ReplyDelete
  62. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also.
    Best Gym in Visakhapatnam

    ReplyDelete

  63. This post is so interactive and informative.keep update more information...
    Azure Training in Bangalore
    Microsoft Azure training in Bangalore

    ReplyDelete
  64. Really an awesome blog and useful content. Keep updating more blogs again soon. Thank you.
    Data Science Course in Hyderabad

    ReplyDelete
  65. Amazing knowledge and I like to share this kind of information with my friends and hope they like it they why I do
    full stack development course

    ReplyDelete
  66. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work
    full stack web development course in malaysia

    ReplyDelete
  67. Магазин спортивного питания, официальный интернет-сайт которого доступен по адресу: SportsNutrition-24.Com, реализует широкий ассортимент спортивного питания, которые принесут пользу и заслуги как профессиональным спортсменам, так и любителям. Интернет-магазин осуществляет свою деятельность уже многие годы, предоставляя клиентам со всей России качественное спортивное питание, а также витамины и специальные препараты - https://sportsnutrition-24.com/bustery-gormona-rosta/. Спортпит представляет собой категорию товаров, которая призвана не только улучшить спортивные достижения, да и благоприятно влияет на здоровье организма. Подобное питание вводится в повседневный рацион с целью получения микро- и макроэлементов, витаминов, аминокислот и белков, а также многих других недостающих веществ. Не секрет, что организм спортсмена в процессе наращивания мышечной массы и адаптации к повышенным нагрузкам, остро нуждается в должном количестве полезных веществ. При всем этом, даже правильное питание и употребление растительной, а также животной пищи - не гарантирует того, что организм получил нужные аминокислоты либо белки. Чего нельзя сказать о качественном питании для спорта. Об ассортименте товаров Интернет-магазин "SportsNutrition-24.Com" продает качественную продукцию, которая прошла ряд проверок и получила сертификаты качества. Посетив магазин, заказчики могут получить для себя товары из следующих категорий: - L-карнитинг (Л-карнитин) представляет собой вещество, родственное витамину B, синтез которого осуществляется в организме; - гейнеры, представляющие из себя, белково-углеводные смеси; - BCAA - средства, содержащие в собственном составе три важные аминокислоты, стимулирующие рост мышечной массы; - протеин - чистый белок, употреблять который вы можете в виде коктейлей; - современные аминокислоты; - а кроме этого ряд других товаров (нитробустеры, жиросжигатели, специальные препараты, хондропротекторы, бустеры гормона роста, тестобустеры и многое другое). Об оплате и доставке Интернет-магазин "SportsNutrition-24.Com" предлагает огромное обилие товаров, которое полностью способно удовлетворить проф и начинающих любителей спорта, включая любителей. Большой опыт позволил фирмы наладить связь с крупнейшими поставщиками и изготовителями спортивного питания, что позволило сделать политику цен гибкой, а цены - демократичными! Например, аминокислоты либо гейнер купить можно по цене, которая на 10-20% ниже, чем у конкурентов. Оплата возможна как наличным, так и безналичным расчетом. Магазин предлагает огромный выбор способов оплаты, включая оплату разными электронными платежными системами, а кроме этого дебетовыми и кредитными картами. Главный кабинет компании размещен в Санкт-Петербурге, но доставка товаров осуществляется во все населенные пункты РФ. Помимо самовывоза, получить товар можно при помощи любой транспортной фирмы, выбрать которую каждый клиент может в личном порядке.

    ReplyDelete
  68. The roles of the Data Scientist and Data Analysts job roles are different. Given under are the tasks of the Data Scientist and Data Analyst respectively.

    Data Science in Bangalore

    ReplyDelete
  69. Join the Best institute for Data Science in Bangalore to achieve your career goals. Learn to manage, store, and protect data that will further help in analyzing customer behavior and provide feedback to make critical decisions. Learn the art of storytelling using the facts derived out of data and present the same user data visualization tools. With the right skills and techniques, you can achieve your career goals in this lucrative field.

    Data Science Training in Jodhpur

    ReplyDelete
  70. Unleash your potential and expand your capabilities with the Data Science Certification Course.
    data science course in malaysia

    ReplyDelete
  71. This is one of the best blog about the implemnting of interface ,visit
    full stack development course in agra

    ReplyDelete

Please provide your valuable comments.