Java 8 Interface vs Abstract Class

Deb :

I went through this question: Interface with default methods vs Abstract class in Java 8

The following part is not clear to me:

The constraint on the default method is that it can be implemented only in the terms of calls to other interface methods, with no reference to a particular implementation's state. So the main use case is higher-level and convenience methods.

I tried creating objects of a concrete class (implementation) inside default method and invoked its instance method, it is working fine. i.e, I don't need to use Interface type as reference to the object.

Then what is meant by the quoted paragraph.

Jack :

That sentence means that a default method is implemented inside an interface, so it doesn't have any access to a real state of an object but just to what the interface itself exposes, since an interface can't declare instance variables.

For example:

abstract class Foo {
 int result;
 int getResult() { return result; }
}

This can't be done in an interface because you can't have any member variable. The only thing you can do is to combine multiple interface methods, which is what it is specified as convenience / higher-level methods, eg:

interface Foo {
  void preProcess();
  void process();
  void postProcess();

  default void processAll() {
    preProcess();
    process();
    postProcess();
  }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459873&siteId=1