Skip to content

Instantly share code, notes, and snippets.

@einarwh
Last active January 2, 2024 17:41
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 einarwh/e463be444725528eab6fedb0ced552ed to your computer and use it in GitHub Desktop.
Save einarwh/e463be444725528eab6fedb0ced552ed to your computer and use it in GitHub Desktop.
Object-oriented Hello World.
import java.io.*;
public abstract class Printer {
protected final PrintStream _stream;
public Printer(PrintStream stream) {
_stream = stream;
}
public abstract void print();
}
public class ChainPrinter extends Printer {
private final char _c;
private final Printer _next;
public ChainPrinter(char c, PrintStream stream, Printer next) {
super(stream);
_c = c;
_next = next;
}
public void print() {
_stream.print(_c);
_next.print();
}
}
public class Terminator extends Printer {
public Terminator(PrintStream stream) {
super(stream);
}
public void print() {
_stream.println();
}
}
public class HelloWorld {
public static void main(String[] args) {
PrintStream ps = System.out;
Printer p =
new ChainPrinter('H', ps,
new ChainPrinter('e', ps,
new ChainPrinter('l', ps,
new ChainPrinter('l', ps,
new ChainPrinter('o', ps,
new ChainPrinter(',', ps,
new ChainPrinter(' ', ps,
new ChainPrinter('W', ps,
new ChainPrinter('o', ps,
new ChainPrinter('r', ps,
new ChainPrinter('l', ps,
new ChainPrinter('d', ps,
new Terminator(ps)))))))))))));
p.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment