Skip to content

Instantly share code, notes, and snippets.

@belun
Created October 14, 2011 15:02
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 belun/1287362 to your computer and use it in GitHub Desktop.
Save belun/1287362 to your computer and use it in GitHub Desktop.
Inner workings of class initialization... fail?!
// Will display: null
public class Weird {
static class Collaborator {
private final String someText;
public Collaborator(String text) {
this.someText = text;
}
public String asText() {
return this.someText;
}
}
static class SuperClass {
Collaborator collaborator;
public SuperClass() {
initializeCollaborator();
}
protected void initializeCollaborator() {
this.collaborator = new Collaborator("whatever");
}
public String asText() {
return this.collaborator.asText();
}
}
static class SubClass extends SuperClass {
String someText = "something";
@Override
protected void initializeCollaborator() {
this.collaborator = new Collaborator(this.someText);
}
}
public static void main(String[] arguments) {
System.out.println(new Weird.SubClass().asText());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment