• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Mock exam question

 
Pete Serafin
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You create a class called A with a final variable called z. Is it possible to have three instances of A, each of which has a different value for z?
The following answer explains that you can do this, but i thought that z was automatically initialized to 0 and since its final, it cant be changed. Why is my thinking wrong???

The following code shows one way to do it:
class A {
static int nth;
final int z;
A() { z = nth++; }
public static void main(String[] args) {
new A(); new A(); new A();
}
}
 
Sean Casey
Ranch Hand
Posts: 625
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this case z is considered a blank final. A blank final is when you declare a final variable without initializing it. If you don't initialize by the time it's used, then it would cause a compiler error. In this instance, you are initializing z in the constructor, so you don't get the compiler error. The reason that the z value is able to change in this example is because you are not explicitly changing the z value. the nth value changes and it just so happens that z aquires that value during initialization. The value of z changes each time z is initialized. If you tried to change the value of z after initialization, then you'd get an error. Note that each time a new A object is created, a blank copy of the final variable z is given to the constructor. The variable nth will change with each new object A because it is a static variable.
[This message has been edited by Sean Casey (edited February 23, 2001).]
[This message has been edited by Sean Casey (edited February 23, 2001).]
 
Sri Enga
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
refer Maha Anna's explantion , it's worth reading.
http://www.javaranch.com/ubb/Forum24/HTML/008281.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic