Skip to content

Abstract Class in C#

Sherif Ahmed

Asked Mar 31, 2009, 8:11 AM EDT1 answer
Share
LinkedInX

I have a basic C# question that I thought I’d seek your help on.

 

In Java the following class structure is legitimate (and makes logical sense as AddInterfaceImpl is an abstract class and should not be obligated to implement all methods from the Interface it implements).

However the equivalent C# code throws error indicating that AddInterfaceImpl does not implement all the methods of the underlying interface).

C# forces me to declare GetString() as an abstract method in AddInterfaceImpl to avoid compiler errors.

Does someone have a logical reason as to why GetString() has to be re-declared as Abstract in the AddInterfaceImpl class ?

 


Java Code (Legal)

C#
public interface AnInterface {
      public String
GetString();
}


public abstract class AnInterfaceImpl
implements AnInterface {
      public
AnInterfaceImpl() {
           
GetString();
      }
}

 

 

C# Equivalent

interface AnInterface

C#
{
string GetString();
}

//Will Throw compilation error
// GetString has to be declared in AbstractImpl as string abstract GetString() in order to avoid compiler errors

public abstract class AbstractImpl
: AnInterface
{
public AbstractImpl()
      {
     
      GetString();
      }
}

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    An interface forces a contract in a class without an implementation of the interfaces members. If you use an interface in C#, you "implement" the interface in a class, meaning you provide an implementation of the interfaces members. Abstract classes are sort of a hybrid between a normal class and an interface, with an abstract class you can only inherit from it, and you must implement any abstract members it has. But you can also write implementation code in the class, I use an abstract class mostly...

    public abstract class Person
    {
       private string name;
      
       protected Person(string name)
       {
          this.name = name;
       }

       public abstract void Work(); // Requires implementation in a derived class
    }

    public class Employee : Person
    {
       private string jobTitle;
      
       public Employee(string jobTitle, string name)
          : base(name)
       {
          this.jobTitle = jobTitle;
       }

       public override Work() // MUST implement
       {
          // employee does something in the implementation of Work.
       }
    }
    0