Difference between Interface and Abstract
- | interface | Abstract |
---|---|---|
Multiple inheritance | A class may inherit several interfaces. | A class may inherit only one abstract class. |
Default implementation | An interface cannot provide any code, just the signature | An abstract class can provide default code or just the details that have to be overridden |
Access Modifier | An interface cannot have access modifiers for properties etc everything is assumed as public | An abstract class can contain access modifiers for method and properties |
Fields and Constants | No fields can be defined in interfaces | Fields can be defined |
Difference Virtual and Abstract
Virtual | Abstract |
---|---|
It says look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality. | No Implementation Only Declaration |
When we use Abstract or Sealed or Interface
We would create an abstract
class, when want to move the common functionality of 2 or more related classes into a base class and when, we don't want that base class to be instantiated.
Sealed
is a C# keyword which is used to seal a class and prevent it to get inherited from any other classes.
Interface help us to develop loosely coupled system, Helps in Dependencies Injection, makes Unit Testing easier.
Can an abstract class have a constructor? If so what is the use?
Yes, an abstract class can have a constructor. In general, a class constructor is used to initialize fields. But it happens before the instantiation of a child-class takes place.
Though you cannot create an instance of an abstract class, we can create instances of the classes that are derived from the abstract class.
Abstract classes can't be directly instantiated. So, it is a good practice to use protected access modifier with abstract class constructor and by using public doesn't make sense.
Questions
Q1) An interface has got four interface methods (m1, m2, m3, m4) and implement these interface methods as follows.
Implement m1() & m2() in base class
Implement m3() & m4() in derived class
A1) Make declare m3, m4 virtual in base class and override it in derived class.
Q2) An two interface has got same method, how can you access differently.
A2)
class Test : A, B {
void A.Hello() { }
void B.Hello() { }
}
public class interfacetest {
public static void Main() {
A Obj1 = new Test();
Obj1.Hello();
B Obj2 = new Test();
Obj2.Hello();
}
}