How to reference non-static variable name from static context?

前端 未结 5 649
闹比i
闹比i 2021-01-21 02:22

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(Strin         


        
5条回答
  •  走了就别回头了
    2021-01-21 02:27

    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();    
    

提交回复
热议问题