0

Hello,

I am getting "non-static variable friends cannot be referenced from a static context" error msg when I complie this program. If I create TreeSet inside the Names method body there is no errors when compiling and it works but that is not how I want it work. Could someone be kind enough to help me out here. Creating TreeSet must remain as private instance variable. Thanks in advance and here is my code. I hope I have formatted the thread correctly this time round.

public class Test
{
  private Set<String> friends = new TreeSet<String>(); //if I bring this in the body of Names method the code will work

  public static void Names()
   {
      
     String[] name1 = { "Amy", "Jose", "Jeremy", "Alice", "Patrick" };
   
   
     for (int i = 0; i < name1.length; i++)
     {
       friends.add(name1[i]); // it's here where there error is occuring
     }
	 System.out.println(friends);
   }
}

Edited by ttboy04: made mistake when editing

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by ttboy04
1

The friends variable only exists when there is an instance of the Test class created using new. The Names() method exists outside of any instance of the Test class.
Either create an instance of the Test class and use object.variable syntax to access the variable
Or remove static from Names() definition
Or make friends static.

how I want it work.

Can you explain how you want it to work?

Edited by NormR1: n/a

Votes + Comments
thanks
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.