Wednesday, July 28, 2010

Java Abstract Class vs. Interface: which one to use?

When to use an abstract class?

1) If you want to declare some sensitive data use abstract class

2) If you want to provide common implementation to all the subclasses then use an abstract class

3) If you want to be free to add new public methods in the future,then use abstract class

4) If you have to provide some default implementation(impl) and others should not use your impl.(should have thier own) except in some rare cases, then use abstract classes

5) Accessing a method may be a bit faster (may not be) when compared to interfaces


Note:1) We can declare a class as abstract without having any of its methods as abstract.The compiler will still accepts it.

2) "abtract" modifier can be applied to toplevel and nested classes.

3) A class implementing an interface can it self be declared as abstract.



When to use an interface?

1) If you want to start implementation from the scratch and your impl. and other's impl. may not be same then use intrefaces

2) If all the future implementations should share the method signatures, then use an interface

3) If you want to make some API and if you are sure that the API lives long in future, then use an interface

4) If you want to provide the implementing classes the opportunity to inherit from other sources at the same time, then use an interface

5) If your implementation changes frequently , then use an interface

6) Accessing a method may be a bit slow, when compared to an abstract class , since an extra redirection is needed to get the actual method from the class which the interface is referring to.


Note:1) Even though we do not specify the fields of an intreface as final or static or public in their declaration , by default compiler treats them as public + static + final.

2) Even though we dont specify an interface method declaration as public or abstract in the declaration, by default the compiler treats then as public + abstract. So be careful while overriding them in the subclasses.

3) Interface methods must not be static or final or strictfp or native.

4) Interfaces can also be nested as in case of classes.

5) Interfaces body declaraations can be empty.
for ex: public interface myinterface{
}
These type of interfaces are called marker types, indicating that they possesses certain properties or behaviour for ex: java.lang.Cloneble,java.io.Serilizable

No comments:

Post a Comment