1

Prior to java 8, I knew when to use Abstract classes and interfaces but after Java 8 introduced default and static methods can be provided in interface. An interface and an abstract class are almost similar except that you can create constructor in the abstract class whereas you can't do this in interface. Apart from this, I want to know when to use Abstract class and when to use Java 8 interfaces in real-world examples.

Ramesh Fadatare
  • 561
  • 4
  • 12
  • 2
    This (using abstract class vs interface) should not change after Java 8 was introduced – Thiyagu Mar 18 '18 at 08:16
  • 2
    Interface methods are only applicable when the methods don't need to directly access the private state of an instance. If you understand the difference between interface methods and methods in an abstract class, you will know when you can use either (or both). Then it is up to you to decide which you *prefer* to use. – Stephen C Mar 18 '18 at 08:18
  • https://stackoverflow.com/questions/19998454/interface-with-default-methods-vs-abstract-class-in-java-8 – Seelenvirtuose Mar 18 '18 at 08:38

2 Answers2

2

By introducing default methods in interface, Java 8 may in some cases removes the need to introduce an intermediary abstract/base class that implements the interface with the default behavior for any subclass.
Sometimes, the abstract/base class is still required for other reasons (legacy, needs to contain fields and so for...) but the subclass of it may still benefit from a default implementation without the need to define it.

So the default implementation defined before Java 8 in the base class may be now defined directly in the interface as default methods.

The stream() method defined in the Collection interface is a good example. AbstractCollection and its subclasses as ArrayList don't need to define it. It is directly inherited from the interface.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

If you need multiple inheritance in java you have to use Interfaces instead of Abstract Class.