1

After searching through google and reading a lot of stuff , I conclude that I may able to decide when to use Interface and when to use abstract class except

If all the methods are abstract and public and in future no need to add any method.

So I want to know what option (Interface or Abstract Class) I use if the above condition arises.

Mahesh Patidar
  • 184
  • 3
  • 15
  • 1
    Note that when you're talking specifically about Java, a class can implement as many interfaces as you like, but can only inherit from one class. (Also, bear in mind that "I definitely won't need to add anything in the future" is just setting yourself up to hear "I told you so" from the nearest person.) – Michelle Aug 20 '13 at 12:11

4 Answers4

1

Java doesn't support multiple inheritance so we can only extends one class, there for it is better to use interfaces. But depending on a situation this can be differ. My opinion as a best practice, interface better than abstract class most of the time.

Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
1

You want to use an interface if you have to define a set of common behaviour on different entities.

You use an abstract class if you want to differ between related entities that share common functionality. The abstract class can then hold the common functionality and define the abstract methods that should be used by subclasses to define their specific behaviour.

Keep in mind though that a class can only extend one other class, but it can inherit from multiple interfaces.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
0
If all the methods are abstract and public and in future no need to add any
method

In Interfaces all functions are by default public and abstract whereas an abstract class can have non abstract methods. So you have your answer!

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
0

Abstract classes are best used when they carry behaviour with them in form of implemented methods which´s functionality is usefull for child classes.

In your case, you should go for an interface.

Tomas Longo
  • 95
  • 1
  • 7