aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Static Variable & Inner Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Static Variable & Inner Class" Watch "Static Variable & Inner Class" New topic
Author

Static Variable & Inner Class

ramaseshan T
Ranch Hand

Joined: Feb 17, 2005
Posts: 30

When we compile and run this program it gives:A1B0A0B1A0B2
Please clarify

1. Irrespective of the instance variables, since static variables are associated with the class, I expected the following values at line 3
name = A1 and counter = 2 (For class A)

But the o/p we see demystify the mentioned concept.why is it so?

2. Static variables for a class are stored in heap and there is only one copy available for all objects. Is this correct?


Ramaseshan T<br />SCJP 1.4
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
There are two A objects.
The first is created by "A a1 = new A();", has the name A0 and is referred to by a1.
The second is created by "void m1() {new A().new B();}" and has the name A1.
m2 and m3 create B objects associated with the A0 object referred to by a1.
[ February 20, 2005: Message edited by: Mike Gershman ]

Mike Gershman
SCJP 1.4, SCWCD in process
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
The first time a class A is referenced in your program, a class object "A.class" is instantiated on the heap. The static variables of that class are placed on the heap with the class object.

The single class object is shared by all instances of the class, so there is only one copy of each static field.
ramaseshan T
Ranch Hand

Joined: Feb 17, 2005
Posts: 30

There are two A objects.
The first is created by "A a1 = new A();", has the name A0 and is referred to by a1.
The second is created by "void m1() {new A().new B();}" and has the name A1.
m2 and m3 create B objects associated with the A0 object referred to by a1.


The second is created by ......and has the name A1---this is what we expect--But it is having a value A0.

If we try to print the value of name in comment 3, we get A0.Why?
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
If we try to print the value of name in comment 3, we get A0.Why?



Since m2 is called on a1 and a1 refers to the first A instance, named A0, this.new on line 3 refers to the object named A0.
 
Consider Paul's rocket mass heater.
 
subject: Static Variable & Inner Class