user3341953
user3341953

Reputation: 319

Why I could only use the method when it is static

I wrote a method just under my main method,

 public static LinkList getContents()

then in the main method LinkList list = getContents()

It could only work when I add static in the declaration of getContents, why?

otherwise it will report an error !

Upvotes: 0

Views: 54

Answers (2)

Kavourosaurus
Kavourosaurus

Reputation: 23

It's a very important concept in Java! Because when calling or referencing things inside of a static method (such as main), you can only reference other static variables, methods, and objects.

Conversely, you can still reference static data from inside non static methods.

The solution for this would be to make an "object" of your class. This starts to get into one of the core concepts of object oriented programming.

Making an object of a class (inside of main) :

ClassName ->pick any name<- = new ClassName();

then you can reference the method like this ->the name you chose.getContents();

Here's some practice code

public class Person{

public void setName(String name){
...
}



 public static void main(String[] args){
    Person bob = new Person();
    bob.setName("pete");

}


}

Upvotes: 0

Wyzard
Wyzard

Reputation: 34563

A non-static method has to be called on a specific instance of the class e.g. anObject.getContents().

Upvotes: 3

Related Questions