The code above is totally fine(although it's meaningless to do so) and the output is 151 154. It makes me surprised that a final variable can be redefined in the method of class with the same name.
nemo zou wrote:It makes me surprised that a final variable can be redefined in the method of class with the same name.
Because of "variable hiding".
The parameter of the Changeit method just happens to have the same name (FinalV) as the class variable FinalV of the FinalValue class. And you can access both in the Changeit method:
And as a final note: remember the Java naming conditions for methods and variables, you should use camelCase notation (so finalValue and changeIt). And classes use CamelCase notation (e.g. InnerClass)
nemo zou wrote:t1.exec(3) is 3 is because exec is a static method, I can understand this point .
Spot-on! The exec method is static, so the type of the reference variable determines which method to execute. In this case the type of t1 is Times, so the Times.exec() method will be executed.
nemo zou wrote:But why does a null object also has static methods/values with it?
For exactly the same reason. To invoke a static method, the compiler is only interested in the type of the reference variable not in the actual object. The type of t3 is Times2, so the Times2.exec() method will be executed. Don't forget: you don't require any object to invoke/access a static method/variable. On the job it's a best practice to always use the class name to invoke/access a static method/variable (instead of a class instance). But on the exam, you might see code like this trying to trick/fool you
You could even write something like thisRemember: this only works with static/class methods, if exec was an instance method, you'll get a NullPointerException (obviously).
Roel De Nijs wrote:
You could even write something like thisRemember: this only works with static/class methods, if exec was an instance method, you'll get a NullPointerException (obviously).
l
Another thing: I thought the following code should print out "This is Times3". But the reality is that it does not print anything out...
nemo zou wrote:Another thing: I thought the following code should print out "This is Times3". But the reality is that it does not print anything out...
That's because your code only requires to load the TestTimes class in memory. Once you invoke the exec method on the reference variable (or the class name), classes Times and Times3 will be loaded in memory and the println statement will be executed.
nemo zou wrote:Another thing: I thought the following code should print out "This is Times3". But the reality is that it does not print anything out...
That's because your code only requires to load the TestTimes class in memory. Once you invoke the exec method on the reference variable (or the class name), classes Times and Times3 will be loaded in memory and the println statement will be executed.