3

Does the Java language guarantee that the instanceof operator or the getClass() method applied to this in a constructor always applies to the deeper class in the hierarchy?

For example, if I want to limit the subclasses which are allowed to call a constructor from the superclass, I could do this:

class A {
  A() {
    final Class<?> clazz = getClass();
    if (clazz != A.class && clazz != B.class && clazz != C.class) {
      throw new IllegalStateException();
    }
  }
}

but I wonder whether the language guarantees that it will work or not.

Michele Dorigatti
  • 811
  • 1
  • 9
  • 17
Julien Royer
  • 1,419
  • 1
  • 14
  • 27
  • While this will work, this isn’t an ideal way to do it. Usually, this is accomplished by having all three classes in the same package, and making the constructor of class A package-protected (as your example code is already doing, by making the constructor neither public nor private nor protected). – VGR Jan 27 '20 at 18:21
  • @VGR I agree that the example is quite ugly. – Julien Royer Jan 28 '20 at 08:59

2 Answers2

3

Yes, it's guaranteed.

There is a always an implicit call to super() as the first action of the constructor if you do not explicitly specify one. (JLS)

The reason this constraint is enforced - rather than allowing the parent constructor to be called at any point - is so that all super classes are guaranteed to be initialized, whether that be Object, or any other super type. Every instance method of Object is safe to use at this point; getClass is no exception.

See also Why do this() and super() have to be the first statement in a constructor?

Michael
  • 41,989
  • 11
  • 82
  • 128
2

Your question is essentially, on which object getClassis called? JLS Covers it as follows

The keyword this may be used only in the following contexts:

  • the body of a constructor of a class (§8.8.7)
  • ...

When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method or default method was invoked (§15.12), or to the object being constructed.

mightyWOZ
  • 7,946
  • 3
  • 29
  • 46