Default methods and interfaces extending other interfaces

This is exactly addressed by the JLS in 15.12.3. “Compile-Time Step 3: Is the Chosen Method Appropriate?”. If the form is TypeName . super . [TypeArguments] Identifier, then: […] If TypeName denotes an interface, let T be the type declaration immediately enclosing the method invocation. A compile-time error occurs if there exists a method, distinct … Read more

How to explicitly invoke default method from a dynamic Proxy?

I’ve been troubled by similar issues as well when using MethodHandle.Lookup in JDK 8 – 10, which behave differently. I’ve blogged about the correct solution here in detail. This approach works in Java 8 In Java 8, the ideal approach uses a hack that accesses a package-private constructor from Lookup: import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Constructor; import … Read more

Java 8 add extension/default method to class

Java doesn’t have extension methods. Default methods are not extension methods. Let’s look at each feature. Default methods Both Java and C# support this feature Problems solved: Many objects may implement the same interface and all of them may use the same implementation for a method. A base class could solve this issue but only … Read more

Calling default method in interface when having conflict with private method

Update: Seems like it’s really a bug. A class or super-class method declaration always takes priority over a default method! default hello(…) method from the Myinterface allows you to write without errors: ClassB b = new ClassB(); b.hello(); Until runtime, because at runtime hello(…) method from the ClassA takes the highest priority (but the method … Read more

Why can we not use default methods in lambda expressions?

It’s more or less a question of scope. From the JLS Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names). … Read more

Do Java 8 default methods break source compatibility?

Doesn’t JDK 1.8 introduce a forward incompatibility for Java source code due to default methods? Any new method in a superclass or interface can break compatibility. Default methods make it less likely that a change in an interface will break compatibility. In the sense that default methods open the door to adding methods to interfaces, … Read more

When is an interface with a default method initialized?

This is a very interesting issue! It seems like JLS section 12.4.1 ought to cover this definitively. However, the behavior of Oracle JDK and OpenJDK (javac and HotSpot) differs from what’s specified here. In particular, the Example 12.4.1-3 from this section covers interface initialization. The example as follows: interface I { int i = 1, … Read more