Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scottashipp/66f3eac5feaff22bda1d1bf8b722844e to your computer and use it in GitHub Desktop.
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
//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