Difference between Abstract Classes and Interfaces
Abstract | ย Interface |
---|---|
Abstract class can have abstract and non-abstract methods ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย ย . | Interface can have only abstract methods and abstract class can have field/property but interface not allow it. |
Abstract class doesn’t support multiple inheritance | Interface supports multiple inheritance. |
Itย can use access modifier | But interface wont have it because within an interface by default everything is public |
Itย can have final, static ,non-final and non-static variables | Interface has only final variables and static |
It can provide the implementation of interface | Interface can’t provide the implementation of abstract class |
Let us discuss the difference one by one with simple example.
Abstract class can have abstract and non-abstract methods. Interface can have only abstract methods and abstract class can have field/property but interface not allow it.
Abstract Class:
1 2 3 4 5 6 7 8 9 10 |
public abstract class Employee { public string FirstName; public string LastName; public override int GetFullName() { return this.FirstName + " " + this.LastName; } } |
Interface : Wrong
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public interface IEmployee { // Cant use field in interface public string FirstName; public string LastName; //Implementation & access specifier will not accept public int GetFullName() { return this.FirstName + " " + this.LastName; } } |
Interface : With Proper
1 2 3 4 |
public interface IEmployee { void GetFullName(); } |
Abstract class doesn’t support multiple inheritance. Interface supports multiple inheritance.
It’s not possible to inherite more than one abstract class. For example, if we having two abstract class namely Employee , EmployeePersonalDetails.
Abstract: Error
1 2 3 4 5 |
//Multiple class can't be inherit. class PartTimeEmployee : Employee ,EmployeePersonalDetails { ... code here.... } |
1 2 3 4 |
class PartTimeEmployee : IEmployee ,IEmployeePersonalDetails { ... code here.... } |
ย An abstract class can access modifier but interface wont have it because within an interface ย everything is public in default.
Interface :ย Incorrect
1 2 3 4 |
public interface IEmployee { public void GetFullName(); } |
Interface : Correct
1 2 3 4 |
public interface IEmployee { void GetFullName(); } |
ย
Leave A Comment