• 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

non-static variable x cannot be referenced from a static context

 
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
NetBeans is giving me the following error on the line "int cx = child.y;" : (line #13)

non-static variable x cannot be referenced from a static context

Can someone explain why I am getting that error?

Thank you.

 
Bartender
Posts: 3225
34
IntelliJ IDE Oracle Spring Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
A Static block/method can access only static methods/variables.

From the code I see that 'y' in class Child is not static and hence you cannot use ClassName.varaibleName format. To access 'y' you would need an instance of child class. Or if you want to use the code as is- You can change 'y' in child class as static.
 
Greenhorn
Posts: 3
Mac OS X Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. class child {
2. int y = 12;
3. public void testIt() {
4. System.out.println("x is blank");
5.
6. // parent p = new parent();
7. //System.out.println("x in parent is " + p.x);
8. }
9. }
10.
11. class testProtect {
12. public void testAccess() {
13. int cx = child.y; <-- whats child here 1 doesn't get related to 2 either pass the reference of 1 or declare the variable as static
14. System.out.println("x is " + cx);
15. }
16. }
17.
18. public class Main {
19. public static void main(String[] args) {
20. child childob = new child(); <-- you define new child object 1
21. childob.testIt();
22. testProtect tp = new testProtect(); <-- new test project here 2
23. tp.testAccess();
24. }
25.
26. }
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
the static code runs even if no instance of the class has been created. So, somewhere in that code, your are asking for a value for a SPECIFIC instance - which has never been created. You're asking for the color of a house that has not been built.
 
reply
    Bookmark Topic Watch Topic
  • New Topic