aspose file tools*
The moose likes Beginning Java and the fly likes Accessing instance  variable inside static reference. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Accessing instance  variable inside static reference. " Watch "Accessing instance  variable inside static reference. " New topic
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
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3056
    
  33

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: 36508
    
  16
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: 36508
    
  16
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Accessing instance variable inside static reference.
 
Similar Threads
Inner Class
Local inner classes
accesing variable of default package inside the package class
Protected
how to access class defined in an interface