Created
May 10, 2016 21:39
-
-
Save scottashipp/66f3eac5feaff22bda1d1bf8b722844e to your computer and use it in GitHub Desktop.
How to force clients to provide an implementation for toString at the compiler level
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1. create the interface with a different method than toString | |
interface Loggable { | |
String toLogString(); | |
} | |
//2. Create an abstract class that forwards toString() to this other method | |
abstract class LoggerBase implements Loggable { | |
public String toString() { | |
return toLogString(); | |
} | |
} | |
//3. Extend the abstract class for the children and "toLogString()" will always get called by conversions toString | |
public class Logger extends LoggerBase { | |
public String toLogString() { | |
return "Hello world!"; | |
} | |
public static void main(String[] args) { | |
Logger l = new Logger(); | |
System.out.println(l); //Hello world! | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment