-1

I am trying to use accessors (Set/Get) methods in my program, and when I try to use the Get method in the main method, I get this error:
Cannot make a static reference to the non-static method getID() from the type Student.

I am unsure how to go about fixing this. I'm a beginner at Java programming.


Here are the particular lines in question:

The set/get methods:

public void setID (String ID) {this.ID = ID;}
public String getID() {return this.ID;}

The error line:

System.out.println(Student.getID());

Any advice would be appreciated!*

A full picture of my code.

Prometheos II
  • 334
  • 3
  • 14
Isiah D
  • 3
  • 3
  • 2
    You want to call `getID()` on an instance of `Student`, not `Student` itself – GBlodgett Feb 05 '19 at 18:29
  • 2
    Hint: You've created two `Student` objects. When you try to call `Student.getID()`, which of those two do you think you're referring to and why? – David Feb 05 '19 at 18:32
  • You should call .getId() on object of Student. – Anuj Vishwakarma Feb 05 '19 at 18:33
  • 2
    You should follow the Java Naming Conventions: variable names *always* start with lowercase. So `ID` should be `id`, `Bob` should be `bob` and `Name` should be `name`. – MC Emperor Feb 05 '19 at 18:33
  • @Isiah deDiego main() method is called by the JVM even before the instantiation of the class hence it is declared as static. – Muhammad Waqas Feb 05 '19 at 18:33

3 Answers3

4

Try something like this...

Student aStudent = new Student();
aStudent.setID("2112");
System.out.println(aStudent.getID());

Notice that I have created an instance of Student and I am asking that instance to return its ID. Student.getID() is asking the Student class to return its ID, and that is not what you have coded, and probably not what you want.

Steve
  • 692
  • 1
  • 7
  • 18
1

You should call the getID() on an instance, not the class itself.

Here's an example from your code:

Bob.getID(); // instead of Student.getID()

And to be even more helpful, I'd advise you to stop hacking your way through before learning about the concepts of a Class/type and a variable/instance.

Prometheos II
  • 334
  • 3
  • 14
kdehairy
  • 2,630
  • 22
  • 27
0

getId() is a non-static method of the Student class and should be invoked on an object, and not on the class itself.

To understand, the id instance attribute would belong to a particular student (like Bob or Thomas) so you should call Bob.getId() or Thomas.getId() which you give you the id attribute of Bob or Thomas respectively.

Prometheos II
  • 334
  • 3
  • 14