The use of instance variables in an explicit constructor invocation is prohibited by the JLS, Section 8.8.7.1.
An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods or inner classes declared in this class or any superclass, or use this
or super
in any expression; otherwise, a compile-time error occurs.
This prohibition on using the current instance explains why an explicit constructor invocation statement is deemed to occur in a static context (§8.1.3).
You referenced the instance variable b
. The compiler didn't raise this error on a
because it's a local variable, which shadows the instance variable a
.
The "static context" may be why your IDE is suggesting to make b
static, so it can be referenced. It makes sense; the ClassName
part of the object isn't constructed yet. Replace that usage of b
with something else, such as a static
constant, or a literal int
value.
To answer your other question, typing new ClassName(a, b)
isn't an error because at this point, this instance has been constructed, and you're creating a separate, unrelated ClassName
object.
ClassName
object in aClassName
constructor. See Paul Boddington's answer for details. – azurefrog 1 hour ago