Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between an interface and an abstract class? [duplicate]

Tags:

java

Possible Duplicate:
Interface vs Abstract Class (general OO)

I'm not exactly clear on the difference.

Thanks

like image 851
jmasterx Avatar asked Nov 08 '10 18:11

jmasterx


People also ask

What is a difference between an interface and an abstract class?

The Abstract class and Interface both are used to have abstraction. An abstract class contains an abstract keyword on the declaration whereas an Interface is a sketch that is used to implement a class.

What is the difference between an interface and an abstract class Mcq?

An abstract class can contain static variables and methods. An interface contains only public static final variables.

What are the similarities and differences between interfaces and abstract classes?

Both Interfaces and Abstract Classes can have methods and variables, but neither of them can be instantiated. All the variables declared within the interface are final. However, the variables declared in Abstract Classes can be non-final and can be modified by the user-defined classes.

Is it better to use interface or abstract class?

If you are creating functionality that will be useful across a wide range of objects, then you must use an interface. Abstract classes, at the end of the day, should be used for objects that are closely related. But the interfaces are best suited for providing common functionality to unrelated cases.


2 Answers

They are quite similar but there are some important technical differences:

  • An abstract class allows you to provide a default implementation for some of the methods but an interface does not allow you to provide any implementations.
  • You can implement multiple interfaces but you can only inherit from one abstract class.

These differences affect how the two techniques should be used:

  • You should use an interface to define a contract.
  • An abstract class can be useful to reuse code... but be aware that it is not the only way to reuse code. You should also consider other approaches such as containment.
like image 184
Mark Byers Avatar answered Oct 18 '22 18:10

Mark Byers


An interface doesn't allow definition of any of the member methods, whereas an abstract class does allow some or all to be defined. A class however can only extend one class (abstract or not) but can implement as many interfaces as it wants.

like image 40
Reese Moore Avatar answered Oct 18 '22 20:10

Reese Moore