Java 8 interface allows default implementations, static method declaration and static final attributes declarations: Here we show an example (just to show the concept) of interface declaration and inheritance. We can add that with the default code, inherited attributes are hidden and we will show the final solution.
Example: In the code bellow we had to redeclare the inherited default method in each interface because the static attributes "from" and "to" were hidden by the super interface Locationable. You can try to remove the methods in subinterfaces to verify.
public interface Locationable { float from = 0; float to = 0; public default int closeTo( float other) { System.out.println(from + " and " + to ); if( other>=from && other<=to) return 1; return -1; } } public interface Southern extends Locationable { float from = 100; float to = 1000; public default int closeTo( float other) { System.out.println(from + " and " + to ); if( other>=from && other<=to) return 1; return -1; } } public interface Northern extends Locationable { float from = 5000; float to = 7000; public default int closeTo( float other) { System.out.println(from + " and " + to ); if( other>=from && other<=to) return 1; return -1; } } public interface Midthern extends Locationable { float from = 1000; float to = 5000; public default int closeTo( float other) { System.out.println(from + " and " + to ); if( other>=from && other<=to) return 1; return -1; } } public class Walker implements Southern,Northern,Midthern{ public int closeTo(float pos) { int r = -1; if( (Southern.super.closeTo(pos) == 1)) { System.out.println("Hey I'm in the South!!"); r = 1; } else if( Northern.super.closeTo(pos) == 1) { System.out.println("Hey I'm in the North!!"); r = 1; } else if( Midthern.super.closeTo(pos) == 1) { System.out.println("Hey I'm in the Midlands!!"); r = 1; }else System.out.println("Hey I'm in the Lymbus!!!!"); return r; } } void interfaces_exec() { Walker walker = new Walker(); for(int i= 0; i < 20; i++) { float pos = (float)(Math.random() * 7000) % 7000; walker.closeTo(pos); }
No hay comentarios :
Publicar un comentario