-3

Possible Duplicate:
java : non-static variable cannot be referenced from a static context Error

My aim is to create a program for client server chat.I wrote the following code https://github.com/jinujd/Java-networking/blob/master/Server.java for the server.. After compilation I got the following error.

non-static variable this cannot be referenced from a static context. What is the problem there? My another doubt is that

/*A.java*/
class A {
    String a;
    class B {
    }
    public static void main() {
    }
}

Is the variable a accessible to B and main() ?

1
  • 1
    This question has been asked numerous times already. Just google for your title to find many answers. Commented Nov 4, 2012 at 15:15

3 Answers 3

2

Static functions/variables are associated with the class definition itself while class variables(non-static) are associated with class instance i.e. they are normally initialized when you instantiate an object from the class.

Static functions/variables can be used without class instance as:

        A.main();

While to access non-static functions/variables, you need to create object instance first:

        A a = new A();
        a.getA();

Since static scope is up in the hierarchy(at definition level), and it doesn't have visibility of instance level methods/variables and hence complains. But opposite is OK i.e. you should be able to access static methods/variables from non-static methods.

Having explained the reason, I believe you would be able to correct the scope of the class/method/variable yourself.

Sign up to request clarification or add additional context in comments.

Comments

1

You need

static class ClientReceiver extends Thread {

Not

class ClientReceiver extends Thread {

1 Comment

You haven't stated that that will only work if the nested class doesn't use instance variables of the outer class, and you haven't described the alternate solution.
1

non-static variable this cannot be referenced from a static context. What is the problem there?

you need an instance of the class to access the non-static data from static context.

    public class Sample {
     String var="nonstatic variable";
    public static void main(String...args){
      Sample s= new sample();
      system.out.println(s.var);

}

} 

your class B can access your string a directly, but your static main method needs an instance of class A to access it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.