• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Outer - Inner class

 
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Getting compile time error as "non-static variable id can not be referenced from static context"

I do not understand why compiler is giving this error. If i remove OuterTest from line, then it gives expected result.
Thank you in advance !

 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to use: OuterTest.this.id to give it the proper context.
 
Nitin Bhagwat
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you for your reply Barry, i understand i should use this to refer "current object". Still, i did not understood, if i am not using "this", what is exact meaning of error i am getting?
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"this" refers the instance of current object, like a reference refers an instance of a object or class. In your code, you used OuterTest.id which is class name followed by a member, in java you can only access a static member by using class name. Althouth reference veriable can access both static and non static member. That is why you got the error.

If you change your code to make id as static, it will work fine.
The way you did by removing OuterTest, it worked fine because id refers the member in your InnerTest which is inherited from OuterTest. So if you use id or this.id, it refers member id of InnerTest, it will give you result "Default". If you use OuterTest.this.id, it refers member id of OuterTest, you can know the result will be STP
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic