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

error: non-static variable this cannot be referenced from a static context  RSS feed

 
Stan Lederer
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got a java program that fails to compile and produces this error:


Here's the code, a modification of this piece of code I found on the Web:

What does this error mean and how can I fix my code?

Thanks very much.
 
Jeanne Boyarsky
author & internet detective
Sheriff
Posts: 37222
519
Eclipse IDE Java VI Editor
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stan,
You have an inner class. Probably not on purpose:


If you unnest the classes, you can write:


The later lets you instantiate "normally." You'll learn about inner classes later, but it's best to avoid them while you are still getting comfortable with the basics. The syntax looks a little weird.
 
Stan Lederer
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So, I refactored my code to not have nested classes and to use a constructor. And, I still get the same compiler error, although I do get past the error in creating the MySQLTest object:

Here's the new code:

I'm very confused. All I can guess is that main is a static method and readDataBase isn't.

I'd appreciate an insight on what I'm missing.

Thanks.
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What you are doing is creating an object, but never using it. You should declare and initialise a reference, or run the two lines together.or
 
Stan Lederer
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:What you are doing is creating an object, but never using it. You should declare and initialise a reference, or run the two lines together.or

Thanks, Campbell, for the explanation. I tried your first solution and that worked great. Clearly I need to get myself grounded in how objects work.
 
Campbell Ritchie
Marshal
Posts: 55672
161
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You’re welcome

To all intents and purposes, both solutions do the same thing. In the second version, however, you can use sqlt again.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!