Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

The reason to cause non-static variable cannot be referenced from a static context  RSS feed

 
Ranch Hand
Posts: 65
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why can't the static variable named "ml" be assigned a reference value in the first place just like another static variable named "f"?
You can compare the two pictures.
The complete code is as follow.

can-t-compile.PNG
[Thumbnail for can-t-compile.PNG]
can-compile.PNG
[Thumbnail for can-compile.PNG]
 
Sheriff
Posts: 4742
131
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I get a different error:

Java Compiler wrote:No enclosing instance of type MiniMusicPlayer is accessible. Must qualify the allocation with an enclosing instance of type MiniMusicPlayer (e.g. x.new A() where x is an instance of MiniMusicPlayer).


This has to do with the class MyDrawPanel being a nonstatic inner class.  As the error says, you need an instance of MiniMusicPlayer to instantiate ml.  So for instance, this works:
So why does it work in the method setUpGui()?  Because at that point in the code, you do have an instance of MiniMusicPlayer: it's called this.  These two lines: ... are semantically equivalent.
 
Crystal Zeng
Ranch Hand
Posts: 65
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you so much.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!