Difference between Interface
and Abstract Class
What is an Abstract
Class?
An abstract class is a special kind of
class that cannot be instantiated. So the question is why we need a class that
cannot be instantiated? An abstract class is only to be sub-classed (inherited
from). In other words, it only allows other classes to inherit from it but
cannot be instantiated. The advantage is that it enforces certain hierarchies
for all the subclasses. In simple words, it is a kind of contract that forces all
the subclasses to carry on the same hierarchies or standards.
What is an Interface?
An interface is not a class. It is an
entity that is defined by the word Interface. An interface has no
implementation; it only has the signature or in other words, just the
definition of the methods without the body. As one of the similarities to
Abstract class, it is a contract that is used to define hierarchies for all
subclasses or it defines specific set of methods and their arguments. The main
difference between them is that a class can implement more than one interface
but can only inherit from one abstract class.
So Is there any other major differences
?
Yes…They are as follows:
·
An
Abstract class can have a combination of abstract and other normal methods Whereas in Interface
it must have only methods (abstract) without definition i.e. Without body.
·
An
Abstract class can have any combinations of member variables i.e. public int, private
String, final int etc
but in case of Interface all the variables must have default access specifier
as public and of type static and final. So Even if you didn’t declare it
explicitly it will be always public.
·
As
all the member variables are declared public that is why an Interface must also
need to
Be declared default as
public. While in case Abstract class such conditions are not mandatory.
When
to use abstract class and interface in Java
Here are some guidelines on when to use an abstract
class and interface in Java:
1.
An abstract class is good if you think
you will plan on using inheritance since it provides a common base class
implementation to derived classes.
2.
An abstract class is also good if you
want to be able to declare non-public members. In an interface, all methods
must be public.
3.
If you think you will need to add
methods in the future, then an abstract class is a better choice. Because if
you add new method headings to an interface, then all of the classes that
already implement that interface will have to be changed to implement the new
methods. That can be quite a hassle.
4.
Interfaces are a good choice when you
think that the API will not change for a while.
5.
Interfaces are also good when you want
to have something similar to multiple inheritance, since you can implement
multiple interfaces.
No comments:
Post a Comment