0

What is wrong with my code? Compiler says non static variable cannot be referenced from a static context

package nestedclass;
public class Nestedclass {

    class Student {

        String name;
        int age;
        long roll;

        public Student(String name, int age, long roll) {
            this.name = name;
            this.age = age;
            this.roll = roll;
        }

        public void show() {
            System.out.println("name : "+name+" age : "+age+" roll : "+roll);
        }
    }

    public static void main(String[] args) {
        //Nestedclass=new Nestedclass();
        Student ob=new Student("ishtiaque",10,107060);
        ob.show();
        // TODO code application logic here
    }
}
picciano
  • 22,341
  • 9
  • 69
  • 82
newbie
  • 41
  • 6

4 Answers4

1

The nested Student class isn't static, that's why the compiler complains. There are a couple of ways to get out of this situation: make Student static, or instantiate Nestedclass and provide a nonstatic method in Nestedclass that does the actual work on an instance of Student, and that you call from main:

private void run() {
    Student ob = new Student("ishtiaque", 10, 107060);
    ob.show();
}

public static void main(String[] args) {
    new Nestedclass().run();
}

or, if you like oneliners you could also do

public static void main(String[] args) {
    new Nestedclass().new Student("ishtiaque", 10, 107060).show();
}

Personally I prefer the second method (with the helper method) as it's easier to refactor afterwards.

fvu
  • 32,488
  • 6
  • 61
  • 79
0

Your inner class is not declared as static; therefore, you cannot access it from the static method main. Change your inner class declaration to static class Student

0

You need to initiate the static class then Use the new of that class in order to initiate the their inner none classes. Or you can declare your Student inner class as static class.

first solution

Student ob = new Nestedclass().new Student("ishtiaque", 10, 107060);

second solution

static class Strung {...}

Hope that helps.

BilalDja
  • 1,072
  • 1
  • 9
  • 17
-2

this will work

   public class Student
    {
         String name;
          int age;
         long roll;

        public Student(String name, int age, long roll) {
            this.name = name;
            this.age = age;
            this.roll = roll;
        }


        public void show()
        {
            System.out.println("name : "+name+" age : "+age+" roll : "+roll);
        }

     public static void main(String[] args) {
        Student ob=new Student("ishtiaque",10,107060);
        ob.show();
    }
  }
ajb
  • 31,309
  • 3
  • 58
  • 84
Vendetta
  • 3
  • 3
  • This will *compile*. But the fact that his class is named `Nestedclass` is a pretty strong hint that he needs to create a nested class. Also his package is named `nestedclass`. – ajb Oct 01 '14 at 21:30