Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
Bud Tippins
Ranch Hand
Posts: 52
  • Mark post as helpful
  • send pies
  • 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.

 
Mohamed Sanaulla
Bartender
Posts: 3179
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • 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.
 
Praveen Palaniswamy
Greenhorn
Posts: 3
Java Mac OS X Ubuntu
  • Mark post as helpful
  • send pies
  • 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. }
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!