Deb
Deb

Reputation: 5649

Java 8 Interface vs Abstract Class

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.

Upvotes: 9

Views: 3947

Answers (3)

The Default Method is Just used to gain A Backword_Compatibility Support . Note That The Priority of Default Method is Low Than a Normal Method(or Higher Level Method) So You Cannot Achived the higher-level and convenience methods

Upvotes: -4

Eugene
Eugene

Reputation: 120848

Problem is that default methods can only "see" what is declared in the interface itself - not in the implementation class. Any state fields that are declared in the class that implements this interface are simply not accessible. But they can access static final fields of the interface:

interface test {
    static final int x = 3;

    public default void changeIt() {
        System.out.println(x); // this would work
        ++x; // this will fail
    }
}

Upvotes: 7

Jack
Jack

Reputation: 133567

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();
  }
}

Upvotes: 13

Related Questions