I'm new to Java. I get this error when running the code below
Cannot make a static reference to the non-static field universityObj
But not getting error while using
University universityObj = new University();
The code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
University universityObj;
public static void main(String[] args)
{
University universityObj = new University();
universityObj.name="Robert";
universityObj.stuno=12;
System.out.println(universityObj.name);
System.out.println(University.university_name);
display();
}
public void nonStaticDisplay()
{
System.out.println(name);
System.out.println(stuno);
}
public static void display()
{
universityObj = new University();
System.out.println(universityObj.name);
}
}
CodePudding user response:
Let's go step by step.
The
display()
method should be non-static because it belongs to and should be used on the specific instance of the University class. Static methods can be used without creating an instance of some class. But in the case of thedisplay()
method, it wouldn't makes sense to do that because you need to display the university name, which firstly should be created and assigned.It's not a good idea to create the object instance
University universityObj
inside the class in your case. Better to leave it only in the main method.The
university_name
name is not static, so you can't access it without the class instance (object) like you're doing right now.University.university_name
should be changed touniversityObj.university_name
.
These steps will bring us to a such piece of code:
public class University {
String name;
int stuno;
String university_name = "Michigan University";
public static void main(String[] args) {
University universityObj = new University();
universityObj.name = "Robert";
universityObj.stuno = 12;
System.out.println(universityObj.name);
System.out.println(universityObj.university_name);
universityObj.display();
}
public void display() {
System.out.println(name);
System.out.println(stuno);
}
}
Other things, which you should consider:
Read about encapsulation.
Use code formatting in your IDE. Example for IntelliJ IDEA.
Check the
toString()
method from theObject
class. It's intended exactly for what you're trying to achieve with yourdisplay()
method.
CodePudding user response:
You might simply pass a reference to the instance you want to be displayed. Like,
public static void display(University universityObj)
{
System.out.println(universityObj.name);
}
CodePudding user response:
just make the variable static. static just refers to if the variable is saved in the stack or in the heap.