How to Reference Non-Static Variable Name from Static Context?

How to Reference Non-Static Variable Name from Static Context?

I am trying to write a code that lets the user enter a team name. Here is my code:

public class Team {
    public String name;

    public static void main(String[] args) {
        System.out.println("Enter name team");
        Scanner tn = new Scanner(System.in);
        name = tn.nextLine();     
    }
}

I understand that "non-static variable name cannot be referenced from a static context". I know that if I take the "static" away from the main then it will work, but:

a) How can I reference it without taking the "static" out?

b) Is there a way to get the users input and assign it straight to the variable "name" i.e. without the:

Scanner tn = new Scanner(System.in);
name = tn.nextLine(); 

Basic questions I know, but I am still a beginner! Many thanks, Miles

1

5 Answers

name is a team name. So you need to instantiate a new Team object and set its name :

public static void main(String[] args) {
    System.out.println("Enter name team");
    Scanner tn = new Scanner(System.in);
    Team team = new Team();
    team.name = tn.nextLine();     
}

static methods do not allow to use the non-static variables directly because non-static/instance variables are initialized in memory on object creation. Hence you need to create an object of the the class and then use the variable. Do something like this:

Team teamObj = new Team();
//now access name variable using teabObj instance
teamObj.name = tn.nextLine();    
0

You can use reflection as follows to access that non static field.

    System.out.println("Enter name team");
    Scanner tn = new Scanner(System.in);
    Team team=new Team();
    Field field=Team.class.getField("name");
    field.set(team,tn.next());
    System.out.println((String) field.get(team));

Live demo for reflection.

Or you can try as follows.

   Team team = new Team();
   team.name = tn.nextLine();   

Live demo

0

Create a Team object if you want.

Team team = new Team();
team.name = tn.nextLine();

Static methods/variables are bound to class. They have no access to non-static variables ( they have no idea on which instance of class they should call the method). You have to create object, and then call the non-static method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.