• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing instance variable inside static reference.

 
Prakash Rai
Ranch Hand
Posts: 106
Eclipse IDE MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Saloon Keeper
Posts: 3159
33
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
pete reisinger
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 106
Eclipse IDE MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks pete reisinger...
Can you give me another example of this.?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49827
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be better for you to try such an example, and show us it.
 
mike ryan
Ranch Hand
Posts: 210
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Hi, I commented on some parts of your code to explain maybe a bit better.Hope it helps you understand better!
 
Sean Clark
Rancher
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is more the example you need:


Hope this helps a bit.

Sean
 
Prakash Rai
Ranch Hand
Posts: 106
Eclipse IDE MyEclipse IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks to all ...
 
Campbell Ritchie
Sheriff
Pie
Posts: 49827
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic