I would like to get a better understanding on how to reference objects in java. Given this code that will raise the error “error: non-static variable this cannot be referenced from a static context”:
public class Catalog {
public class Student {
public String name;
...
}
//Student
public static void main (String[] args){
Student s;
s = new Student();
}//main
Q1: Why does it work if class Student is defined in another file “Student.java”?
If I want to keep the Student class definition in the same file with main subroutine, the workaround found on the post “Non-static variable cannot be referenced from a static context” is:
public class Catalog {
public class Student {
public String name;
...
}
public static void main (String[] args){
oopExample prg;
prg = new oopExample();
prg.run();
}//main
Student std1;
public void run(){
std1 = new Student();
std1.name = "Tobby";
}
}//oopExample
Q2: Can you tell me if this is similar from the program execution point of view with case when I use the Student class definition in a separate file?
Q3: What would be the drawbacks of declaring Student as static? and simply use the following code:
public class Catalog {
public static class Student {
public String name;
...
}//Student
public static void main (String[] args){
Student s;
s = new Student();
}//main
Thank you for your time,