Why can I not access an instance of class that is created in a constructor ( Java )

theraveboss :

To preface the question, I'm very new to Java.

I have classes called, Game, Player, and SystemIO. My main() is in the Game class. Below is it's code

public static void main(String[] args){
SystemIO systemIO = new SystemIO();
}

Once SystemIO is called, it's constructor creates an instance of Player with the line

 Player player = new Player("Bob");


where the Player constructor takes 1 argument as a String.

Further down in the SystemIO class I have a method that accesses information from "player" the instance.

player.getName();

When I try to do this, the console reports
SystemIO.java:339: error: cannot find symbol

I have checked that I am not trying to reference the class name with a capital "Player." Like I said, I'm extremely new to Java and just trying to wrap my head around it and I believe it's a scope issue...but I'm not sure.

Edit to add reproducible code:

Game.java

package com.myapps;
import com.myapps.system.SystemIO;

public class Game{
    public static void main(String[] args){
        SystemIO systemIO = new SystemIO();
    }
}

Player.java

package com.myapps.player;

public class Player{
    String name;
    public Player(String playerName){
        name = playerName;
    }
}

public String getName(){
    return name;
}

SystemIO.java

package com.myapps.system;
import com.myapps.player.Player;

public class SystemIO{
    public SystemIO(){
        Player player = new Player("Bob");
        readPlayerName();
    }

    public void readPlayerName(){
        System.out.println(player.getName());
    }
}
Tom De Coninck :

Make player a class variable.

Put someone in your class:

Player player;

and change the code of your constructor to:

player = new Player("Bob");

This is called a scope error. A variable that you want to be accessable to ALL the methods of the class, should be declared IN the class and not in ONE specific method (in your case, you did it in the constructor)

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=403582&siteId=1