0

There are many questions on this site about this. I browsed through all of them and also the internet without finding a solution to my particular problem (or being able to see how they relate to it). Also, what might be unique here is that this is a java specific problem and it doesn't apply to c#. I do some thing really simple here (in java), create a class like so -

public class asdf{
    public int aa;
    public int bb;
    public asdf(int i,int j){
        aa=i;
        bb=j;
    }
}

Now I try to instantiate it from the main method of another class -

asdf aaaa = new asdf(1,2);

Here is the complete code in the test class -

public class test2 {
public class asdf{
    public int aa;
    public int bb;
    public asdf(int i,int j){
        aa=i;
        bb=j;
    }
 }
  public static void main(String[] args){
     asdf aaaa = new asdf(1,2);
  }
}

This line gives me the error - non static variable can't be referenced from a static context. What is static here? The main method is in a class that isn't static, non of the variables are static and I am creating an instance. So, whats the problem? Note also that this works perfectly well in C#. So, it seems to be a Java specific thing.

Rohit Pandey
  • 2,443
  • 7
  • 31
  • 54

2 Answers2

1

Until you understand all about inner classes and static inner classes, it might be best if you define each class in a separate file. Keep the asdf class in a file of its own (and PLEASE use a capital letter at the start of the class name) and remove it from the test2 class. Run the test2 class, and this should all work, without having to declare anything as static.

Come back to this issue and try again once you've started reading about inner classes.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
0

The problem is that your inner class asdf is being instantiated when you create it from the main method.

The simplest way is to make asdf class static. Otherwise you can only create an asdf instance from inside a test2 instance.

dkatzel
  • 31,188
  • 3
  • 63
  • 67
  • Right, that fixed the error, but I still don't understand. If i say its static, how come I am instantiating it? – Rohit Pandey Aug 29 '13 at 02:16
  • See this SO question: http://stackoverflow.com/questions/70324/java-inner-class-and-static-nested-class – dkatzel Aug 29 '13 at 02:19
  • Also, in C#, the opposite happens, Calling it static creates an error while without the static keyword, it is fine. – Rohit Pandey Aug 29 '13 at 02:24