Using an interface as a parameter

You can define methods that take an interface as a parameter. Your interface defines a contract and your methods will accept as parameter any objects whose class implements that interface. This is in fact one of the most common and useful ways to use an interface. interface Test { public void test(); //define the interface } class Tester { public void runTest(Test t) { t.test(); } // method with interface as param } MyTest class will implement this interface:...

April 20, 2017 · 1 min · Rezha Julio

Future of Interface in Java 9

Interface is a very popular way to expose our APIs. Until Java 7 it was getting used as a contract (abstract method) where a child class was obliged to implement the contract; but after Java 8, Interface got more power — to where we can have static and default methods. In Java 9, Interface is getting more power, to the point where we can define private methods as well. Let us understand why we need private methods in Interfaces....

April 13, 2017 · 4 min · Rezha Julio

More about Interface in Java 8

Interface was meant to define a contract before Java 8, where we were able to define the methods a class needed to implement if binding himself with the interface. Interface was only involved with abstract methods and constants. But in Java 8, Interface has become much more, and now it can have methods defined using static or default. Remember that default methods can be overridden, while static methods cannot. Method Definitions Interface was meant for good designers because when we create an Interface, we should know the possible contract that every class should implement....

April 12, 2017 · 4 min · Rezha Julio

Updating interfaces by using default methods

Take the following interface: public interface Cooking { public void fry(); public void boil(); public void chop(); } To add new functionality, simply adding a new method to Cooking called microwave() will cause problems. Any class that previously implemented Cooking will now have to be updated in order to function again. To avoid this, give microwave() a default implementation: public interface Cooking { public void fry(); public void boil(); public void chop(); default void microwave() { //some code implementing microwave } } As microwave() already has a default implementation defined in the Cooking interface definition, classes that implement it now don’t need to implement microwave() in order to work....

April 9, 2017 · 1 min · Rezha Julio