Tuesday, May 22, 2012

How to decide between abstract and interface?

What is difference between following interface and abstract class:



 public interface MyInterface
{
public int get1();
public int get2();
public int get3();
}

public abstract class MyAbstract
{
public abstract int get1();
public abstract int get2();
public abstract int get3();
}


Interviewer was not convinced with following answers, he wanted to hear something else:




  1. I have to extend MyAbstract and then I cannot have more extends, whereas in case of implementing MyInterface I am open to have inheritance.


  2. I have to provide implementation of all three methods if used "implements MyInterface", whereas in case of "extends MyAbstract" I am open to carry forward abstractness.


  3. Design perspective: All libraries work on interfaces not on abstract classes, it is good design practice to use interfaces so that at any time in future I can create any class (implements MyInterface) that can be used in some method of library. (basically same as point one)




What else there could be? I am not concerned with the variables in interface/abstract class etc. How to decide which one to use?





No comments:

Post a Comment