this() vs. super()

This is just going to be another rambling about an inconvenient situation that occurs often in Java. Nothing concrete, no plans of mine to do anything about it any time soon.

Constructors are quite special: They can initialize final fields. You may call another method, a special method only called in the constructor, yet in that method, final methods cannot be initialized anymore. Such a method would be tremendously useful to increase code reuse:

1
2
3
4
5
6
7
8
9
10
class A {
  private final Object _something = null;
  public A() {
    /* do something */
  }
  public A(Object o) {
    /* do something */
    _something = o;
  }
}

It would be nice to get the /* do something */ factored out into a method. In this case, of course, a this() call can help:

1
2
3
4
5
6
7
8
9
10
class A {
  private final Object _something = null;
  public A() {
    /* do something */
  }
  public A(Object o) {
    this();
    _something = o;
  }
}

The situation I ran into now is similar, except that I had a super class and needed to make a super() call as well:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class S {
  protected final Object _something = null;
  public S() { }
  public S(Object o) {
    _something = o;
  }  
}

class A extends S{
  public A() {
    /* do something */
  }
  public A(Object o) {
    super();
    this(); // error: this() must be first statement
  }
}

If I still want to use this() to factor code out, I have to put the super() call second, that’s not allowed, and vice versa.

Besides removing some restrictions for methods called from the constructor, are there any good reasons why this() could not be called after the super() call?

Share

About Mathias

Software development engineer. Principal developer of DrJava. Recent Ph.D. graduate from the Department of Computer Science at Rice University.
This entry was posted in Ramblings. Bookmark the permalink.

One Response to this() vs. super()

  1. Aviad says:

    I am only guessing, but maybe the fear is for virtual methods to be called on “this” from “super”‘s constructor before “this” was initialized?

Leave a Reply