Alex Alex - 1 year ago 80
Java Question

Accessing information from an instance, made by another class

I just started studying software development, and the degree teaches us java through blueJ for the first semester.

I've been doodling around with java programmig for the past 3 weeks now, it's fun and interesting, but I've run into the same problem several times.

"non-static variable cannot be referenced from a static context"

And I know this is a frequently asked question, and I have been reading at least 10 other posts about the error above.

GitHub link:

(I have a blueJ project link too, if anyone prefers that - but I don't have enough reputation to make more than 2 links in a post yet.)

In the code provided above (in either BlueJ or GitHub format), the error occurs in the class 'Responder' when we try to reference 'Game.player.getName()'.

'player' is an instance initialized in the Game class, of the type Player. And I'm trying to acccess the name of the intialized player.

I've tried to re-write the code in several different ways, but I can't make it work with my current experience.

I would absolutely love if someone could explicitly explain to me: why it doesn't work, so I don't repeat the mistake, and how to make it work :)

Visualization of how I view the problem:

I don't know if it will be helpful at all, I mainly made it for myself in an attempt to understand the problem better. However, my way of thinking of the problem might be wrong?

Answer Source

Given the line:

 return "Welcome, " + Game.player.getName();

It tries to acces the class Game and it's static member player, static here mean that player is a mmber of the class, not an instance of it.

The difference between a class and it's instance is like the difference between the idea of a tomato and a concrete tomato. You cannot ask for the color of a general tomato, you must have specific tomato in your hand for that. But you can ask about the botanical properties of a tomato - those are shared for all real life tomatos and are part of the "class".

To fix your problem, you either have to give your function an instance of the class Game, or redifine player to be a static member of Game.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download