Java interface throws an exception but interface implementation does not throw an exception?

A general rule of implementing and extending is you can make your new class or interface “less restrictive” but not “more restrictive”. If you think of the requirement to handle an exception as a restriction, an implementation that doesn’t declare the exception is less restrictive. Anybody who codes to the interface will not have trouble … Read more

Java casting in interfaces

When you cast o1 and o3 with (I2), you tell the compiler that the class of the object is actually a subclass of its declared type, and that this subclass implements I2. The Integer class is final, so o3 cannot be an instance of a subclass of Integer: the compiler knows that you’re lying. C1 … Read more

Attributes / member variables in interfaces?

The point of an interface is to specify the public API. An interface has no state. Any variables that you create are really constants (so be careful about making mutable objects in interfaces). Basically an interface says here are all of the methods that a class that implements it must support. It probably would have … 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

Constructor in an Interface?

Taking some of the things you have described: “So you could be sure that some fields in a class are defined for every implementation of this interface.” “If a define a Interface for this class so that I can have more classes which implement the message interface, I can only define the send method and … Read more

tech