Java 8 Interface Enhancements - default & static
- schick09
- Nov 12, 2023
- 2 min read
Updated: Apr 25, 2024
Java 8 also introduced a few interesting changes to the good old Java Interface. You can now code an implementation method directly in the interface using the default and/or static keywords.
In the following example, we’ve defined a Car interface like so –
package funwithjava8defaultmethods; public interface Car { void setUpAWD(String awdDetails); default void log (String logMessage){ System.out.println(logMessage); } static void print (String str){ System.out.println(str); }; }
Notice there are two method implementations – one default and one static. The default method can be called on a class type that implements the Car interface. The static method can be called from the Car interface only.
To illustrate, let’s define a class called Genesis that implements the Car interface –
package funwithjava8defaultmethods; public class Genesis implements Car { @Override public void setUpAWD(String awdDetails) { System.out.println("AWD input: " + awdDetails); } }
And finally here’s a simple java application demonstrating how the default and static interface implementations are invoked:
package funwithjava8defaultmethods; /** * Java 8 introduced the ability to define * methods in an interface. See below for * examples of static and default interface * method implementations */ public class Main { public static void main(String[] args) { /* * Genesis is a class that implements the * Car interface. * * The Car interface defines a method definition 'setUpAWD' * that must be implemented in the Genesis class. * * The Car interface also defines a default method * implementation called 'log' that is actually implemented * in the Car interface class itself. * * The Car interface also defines a static method * implementation called 'print' that is also implemented * in the Car interface class itself. * * This use of 'default' and 'static' method implementations * in an Interface is new with Java 8 */ Genesis genesis = new Genesis(); genesis.setUpAWD("all wheel drive tech data"); genesis.log("AWD setup complete"); Car.print("Car setup complete"); } }
Here's a link to our GitHub location to access this code example: https://github.com/daveschickconsulting/java_8_examples/tree/main/src/funwithjava8defaultmethods

Comments