简体   繁体   中英

Calling interface Implemented class methods

I am creating object from interface class with implementation class reference, but my problem is I am not able call method of derived class using object.

I am not able call implemented class method after creating object from interface?

class Demo : Iabc
{
  public static void Main()
  {
     System.Console.WriteLine("Hello Interfaces");
     Iabc refabc = new Demo();
     refabc.xyz();
     Iabc refabc = new Sample();
     refabc.xyz();  
     refabc.Calculate(); // not allowed to call Sample's own methods     
   }

  public void xyz()
  {
      System.Console.WriteLine("In Demo :: xyz");
  }  
}

interface Iabc
{
      void xyz();
}

class Sample : Iabc
{
   public void xyz()
   {
       System.Console.WriteLine("In Sample :: xyz");
   }  
   public void Calculate(){
       System.Console.WriteLine("In Sample :: Calculation done");

   }
}

You have to cast refabc to Sample :

  // refabc is treated as "Iabc" interface
  Iabc refabc = new Sample();
  // so all you can call directly are "Iabc" methods
  refabc.xyz();  

  // If you want to call a methods that's beyond "Iabc" you have to cast:
  (refabc as Sample).Calculate(); // not allowed to call Sample's own methods  

An alternative is to declare refabc as Sample instance:

  // refabc is treated as "Sample" class
  Sample refabc = new Sample();
  // so you can call directly "Iabc" methods ("Sample" implements "Iabc")
  refabc.xyz();  

  // ...and "Sample" methods as well
  refabc.Calculate(); 

Side note : it seems, that implementing Iabc in Demo class is redundant . I'd rather put it like that:

  // Main method is the only purpose of Demo class
  static class Demo  { // <- static: you don't want to create Demo instances
    public static void Main() { 
      // Your code here
      ...
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM