| Author |
Accessing instance variable inside static reference.
|
Prakash Rai
Ranch Hand
Joined: Jan 10, 2011
Posts: 101
|
|
Q1.Here variable int a is instance variable and main method is static . so How can I access instance variable inside static context?
|
 |
Mohamed Sanaulla
Bartender
Joined: Sep 08, 2007
Posts: 2928
|
|
You are accessing the instance variable via the instance which is perfectly fine.
And Suppose a1 was declared at the class level- Instance variable then the current usage would have given an error- a1 is being referred in a static context
|
Mohamed Sanaulla | My Blog
|
 |
pete reisinger
Ranch Hand
Joined: Dec 30, 2009
Posts: 46
|
|
|
maybe it is confusing for you because the code is inside static method, but you are creating instance, and calling method on that instance, you are not just calling method (which wouldn't be possible)
|
 |
Prakash Rai
Ranch Hand
Joined: Jan 10, 2011
Posts: 101
|
|
Thanks pete reisinger...
Can you give me another example of this.?
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
|
It would be better for you to try such an example, and show us it.
|
 |
mike ryan
Ranch Hand
Joined: Aug 08, 2010
Posts: 210
|
|
Hi, I commented on some parts of your code to explain maybe a bit better.Hope it helps you understand better!
|
 |
Sean Clark
Rancher
Joined: Jul 15, 2009
Posts: 377
|
|
This is more the example you need:
Hope this helps a bit.
Sean
|
I love this place!
|
 |
Prakash Rai
Ranch Hand
Joined: Jan 10, 2011
Posts: 101
|
|
|
Thanks to all ...
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32708
|
|
mike ryan wrote:
Hi, I commented on some parts of your code to explain maybe a bit better.Hope it helps you understand better!
Not convinced. The reason access is denied is that you are trying to use an instance member of class A as if it were a static member. If you tried that inside an instance method, like this . . . . . . you would suffer the same compiler error. Sean Clark's example answers the original question better.
|
 |
 |
|
|
subject: Accessing instance variable inside static reference.
|
|
|