Sunday, 4 February 2018

The following are the difference between abstract class and interface :
1)
A sub class can inherit/extends from only one abstract class i.e. multiple class inheritance is not supported in c# and java
eg:
public abstract class Animal
{
}
public abstract class Vertebrate
{
}
public class Dog : Animal,Vertebrate
{
//invalid
}
A Sub class can implement any number of interfaces i.e. multiple interface inheritance is supported in c# and java
eg:
public interface IAnimal
{
}
public interface IVertebrate
{

}
public class Dog : IAnimal,IVertebrate
{
//valid
}
2)
An abstract class can have both abstract and non abstract(concrete methods)
eg:
public abstract class Animal
{
public abstract void Breath();//valid
public void HasBackbone()//valid
{

}
}
An Interface should have only abstract  methods
eg:
public interface IAnimal
{
void Breath();//valid
void HasBackbone()//invalid
{
}
}
3)
An abstract class contains fields

eg:
public abstract class Animal
{
int i;//ok
}
An interface does not contain fields.
eg:
public interface IAnimal
{
int i;//invalid
}
4)
An abstract class can have constructor

eg:
public abstract class Animal
{
public Animal()
{
//Ok
}
}
An interface can't have constructor
eg :
public interface IAnimal
{
public IAnimal()
{
//Invalid
}
}
5)
Members of abstract can have access modifiers and default access modifiers of data member and member function/method inside an abstract class by default private and class itself has internal access modifier

eg :
abstract class Animal
{
public abstract void CanBreath();//Ok
}
Member function/method of interface cannot have access modifiers and by default all member function/method inside interface are public and interface itself has public access modifier
eg:
interface IAnimal
{
public void CanBreath();//invalid
}
6)
A sub class should not override/implement all methods inside abstract class and only override/implements abstract method

eg:
abstract class Animal
{
public abstract void CanBreath();
public  virtual void HasBackbone()
{

}
}

class Dog : Animal
{
public override void CanBreath()
{

}
}
A sub class should implement all the methods inside interfaces.
eg:
interface IAnimal
{
void CanBreath();
void HasBackbone();

}

class Dog : IAnimal
{
public void CanBreath()
{
}
public void HasBackbone()
{
}
}

0 comments:

Post a Comment

Powered by Blogger.

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page