• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static Variable & Inner Class

 
ramaseshan T
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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?
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic