Here is my interface example
public interface Card {
String name();
}
I use it in ArrayList and create objects like this.
public static void main(String[] args) {
List<Card> cards = new ArrayList<>();
cards.add(() -> "2");
cards.add(() -> "4");
System.out.println(cards);
}
How can I print a number to console if I create an object like this? Here is the example of the printed text.
[d$$Lambda$14/0x0000000800bb1438@2d98a335]
But I want 2 and 4 to be printed out.
CodePudding user response:
Try this.
public interface Card {
String name();
static Card of(Supplier<String> supplier) {
return new Card() {
@Override public String name() { return supplier.get(); }
@Override public String toString() { return name(); }
};
}
}
public static void main(String[] args) {
List<Card> cards = new ArrayList<>();
cards.add(Card.of(() -> "2"));
cards.add(Card.of(() -> "4"));
System.out.println(cards);
}
output:
[2, 4]
Note: You can't override toString() method.
public interface Card {
String name();
public default String toString() { // compile error
// "A default method cannot override a method from java.lang.Object "
return name();
}
}
