1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| import java.util.Objects;
interface MyTrait {
public void greetings(); // service hérité, programmation générique
}
class B implements MyTrait {
private final String foo = "Hi, I'm a B object.";
@Override
public void greetings() {
System.out.println(this.foo);
}
}
public class MyClass implements MyTrait {
private final String foo;
public MyClass(String foo) {
this.foo = Objects.requireNonNull(foo, "foo cannot be null");
}
public MyClass() {
this("Hello there!");
}
public static void main(String args[]) {
final B b = new B();
final MyClass mc = new MyClass("Hi, I'm a MyClass object!");
MyClass.sayHello(mc);
MyClass.sayHello(b);
}
private static void sayHello(MyTrait mt) {
mt.greetings();
}
@Override
public void greetings() {
System.out.println(this.foo);
}
public static <T> T foo(T a) {
System.out.println("I'm a T objet ! :)");
return a;
}
} |
Partager