Core Java
core14InterfacesDemo
- Path
- pkg1core/core14InterfacesDemo.java
- Package
- pkg1core
- Study order
- 15
- Run
- Single-file source launch
- Command
- java pkg1core/core14InterfacesDemo.java
- Lesson
- Back to the chapter
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg1core;2 3/*4 * core14InterfacesDemo.java5 * -------------------6 * Interfaces: contracts, default & static methods, multiple inheritance of type,7 * private interface methods, and functional interfaces.8 *9 * EXPLANATION:10 * - An interface defines a contract (abstract methods).11 * - `default` methods provide an implementation (added in Java 8) so interfaces12 * can evolve without breaking implementers.13 * - A class can implement MANY interfaces (multiple inheritance of TYPE).14 */15public class core14InterfacesDemo {16 17 interface Greeter {18 String name(); // abstract19 default String greet() { // default method20 return prefix() + name(); // can call private helper21 }22 private String prefix() { return "Hello, "; } // private interface method23 static Greeter of(String n) { return () -> n; } // static factory; lambda impl24 }25 26 interface Swimmer { default String act(){ return "swims"; } }27 interface Flyer { default String fly(){ return "flies"; } }28 29 // Multiple interfaces30 static class Duck implements Swimmer, Flyer {31 String describe() { return "Duck " + act() + " and " + fly(); }32 }33 34 public static void main(String[] args) {35 Greeter g = Greeter.of("World"); // implemented via lambda (functional)36 System.out.println(g.greet());37 38 System.out.println(new Duck().describe());39 40 // Interfaces enable programming to an abstraction41 Greeter custom = () -> "Custom";42 System.out.println(custom.greet());43 }44}