• Post Reply Bookmark Topic Watch Topic
  • New Topic

Hiding Static Methods [From Jeanne Boyarsky - Page 252]  RSS feed

 
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why following piece of code throwing compiler error?

Bear.java

Panda.java


Error:
C:\Practice>javac Bear.java

C:\Practice>javac Panda.java
Panda.java:3: error: non-static variable super cannot be referenced from a static context
                super.eat();
                ^
1 error
 
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
jnrohit Jain wrote:Why following piece of code throwing compiler error?

C:\Practice>javac Panda.java
Panda.java:3: error: non-static variable super cannot be referenced from a static context
                super.eat();
                ^
1 error


Well, the error message is pretty clear, isn't it?  ... but explained in a different way. Static methods are not attached to any particular instance. Hence, they do not have access to the this or super variable, which are used by instance methods to get to their "assigned" object (I am using "assigned" here, for lack of a better word. My brain seems to not have woken up yet... ).

Henry
 
Marshal
Posts: 56608
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If they changed the error message to read
Instance variable myVariable can only be accessed from instance context.
I think it would be easier to understand. The traditional message tempts people to make things static, whereas the correct answer is to remove the keyword static elsewhere.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!