Vaibhav Sagar wrote:Hi, I have a confusion regarding the "this" keyword. I don't understand why the below code runs. Aren't instance variables intialised before the constructor runs?
JSE does indeed say "The keyword this may be used only in the body of an instance method, instance initializer, or constructor, or in the initializer of an instance variable of a class. If it appears anywhere else, a compile-time error occurs.". But how does it actually work out?
Fred Kleinschmidt wrote:The 'this' keyword should never be used this way when initializing instance variables. [...]
The problem is that the instance is not fully complete before the constructor finishes, so this.xxx() may try to reference things that are not yet initialized.
Instance initializers are permitted to refer to the current object via the keyword this (§15.8.3), to use the keyword super (§15.11.2, §15.12), and to use any type variables in scope.
Use of instance variables whose declarations appear textually after the use is sometimes restricted, even though these instance variables are in scope.
More likely that the little girl is now 60 years old
Vaibhav Sagar wrote: . . .
1. Line 7 will print the modified date.
2. Because we still have a reference to the object that was passed to the constructor.
3. Creating a new date inside the constructor or not providing a constructor that takes in a Date in the first place(instead forcing the user to use the setDateOfBirth method which in turn creates a new Date). . . .