Difference between Abstract Classes and Interfaces

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:

public abstract class Employee
{
public string FirstName;
public string LastName;

public override int GetFullName()
{
return this.FirstName + " " + this.LastName;
}
}

Interface : Wrong

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

public interface IEmployee
{
void GetFullName();
}

Note : In simple, An abstract class can has implementation or non-implemented methods but interface can’t have implementation for any of its method.

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

//Multiple class can't be inherit. 
class PartTimeEmployee : Employee ,EmployeePersonalDetails
{
... code here....
}

Interface: It support multiple inheritance

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

public interface IEmployee
{
public void GetFullName();
}

Interface : Correct

public interface IEmployee
{
void GetFullName();
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.