Reputation: 10239
In Java 8 we were introduced to a feature called "Default Methods"
How does Java behave when i try this:
An Interface that has an implementation of doStuff
public interface MyInterface {
default void doStuff() {
System.out.println("MyInterface ");
};
}
And an abstract class that has an implementation of doStuff
public abstract class MyAbstract {
public void doStuff() {
System.out.println("MyAbstract ");
};
}
And a class that extends the abstract class and implements my interface:
public class MyClass extends MyAbstract implements MyInterface {
//this can just be empty
}
Does this even compile? If so, what will be printed when:
new MyClass().doStuff();
Upvotes: 1
Views: 62
Reputation: 5259
Yes
It will print MyAbstract
If the function is not implemented in your class/its parent class, then and only then the default method will be executed. Comment out the method doStuff()
in abstract class and then you have MyInterface
printed out. This way, if someone adds a default method to an interface that you had already implemented with the same method name of a method in your class/parent class, your implementation is not broken
Upvotes: 3