Simple Java Compilation Error

Discussion in 'OT Technology' started by doggfather, Apr 22, 2006.

  1. doggfather

    doggfather New Member

    Joined:
    Aug 6, 2005
    Messages:
    224
    Likes Received:
    0
    public class C {
    private int j;
    public static void main(String[] args) {
    TempClass temp = new TempClass(2);
    System.out.println(temp);
    }

    class TempClass {
    int i;
    public TempClass(int j) {
    int i = j;
    }
    }

    }




    I get C.java:6: non-static variables this cnanot be referenced from a static context
    TempClass temp = ^new TempClass(2);

    1 error
     
  2. Peyomp

    Peyomp New Member

    Joined:
    Jan 11, 2002
    Messages:
    14,017
    Likes Received:
    0
    Perhaps i should be static, as in "static int i;"

    Why do you declare private int j in another class when you use it as an instance variable below? Don't overlap namespace like that. Remove the private int j from above.
     
    Last edited: Apr 22, 2006
  3. Penguin Man

    Penguin Man Protect Your Digital Liberties

    Joined:
    Apr 27, 2002
    Messages:
    21,696
    Likes Received:
    0
    Location:
    Edmonton, AB
    My initial thought is that you've probably bracketed it wrong. Surely you don't intend to define class TempClass inside of your main method?

    If you do, then I have no fucking clue what the problem is or why you would want to do such a thing.
     
  4. Joe_Cool

    Joe_Cool Never trust a woman or a government. Moderator

    Joined:
    Jun 30, 2003
    Messages:
    299,488
    Likes Received:
    616
    I'm not sure whether it's the best solution or not, but it compiles and runs if you change the inner class definition (line 8) to say

    static class TempClass{
     

Share This Page