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.
Abstract classes can have methods with implementation whereas interface provides absolute abstraction and can't have any method implementations. Note that from Java 8 onwards, we can create default and static methods in interface that contains the method implementations.
Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing a common functionality to unrelated classes. Interfaces are a good choice when we think that the API will not change for a while.
After Java 8, an interface can have default and static methods along with abstract methods. Interfaces don't support final methods. But, abstract classes support final as well as non-final methods and static as well as non-static methods along with abstract methods.
Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables. Implementation: Abstract class can provide the implementation of the interface. Interface can't provide the implementation of an abstract class.
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
}
}
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With