Win a copy of Head First Android this week in the Android forum!
  • 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:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Hiding Static Methods [From Jeanne Boyarsky - Page 252]

 
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Posts: 23909
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 74371
334
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic