- A Concurrent Affair - https://www.concurrentaffair.org -

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 [1] _something = null;
  public A() {
    /* do something */
  }
  public A(Object [1] 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 [1] _something = null;
  public A() {
    /* do something */
  }
  public A(Object [1] 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 [1] _something = null;
  public S() { }
  public S(Object [1] o) {
    _something = o;
  }  
}

class A extends S{
  public A() {
    /* do something */
  }
  public A(Object [1] 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?

[2] [3]Share [4]
1 Comment (Open | Close)

1 Comment To "this() vs. super()"

#1 Comment By Aviad On January 24, 2008 @ 00:53

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?