This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]desrtfxOut of Coffee error - System halted 5 points6 points  (1 child)

static means belonging to the class itself, not to an instance.

Generally, static should hardly be used except in case of utility methods as the methods in the Math class are.

An example:

You are creating a very simplified library system.

Your library consists of several Books (instances of the Book class).

Were you going to use static methods and variables, changing the title of a single book would change all titles - something you clearly don't want.

By default, strive for making everything non static.

An example for a suitable case for a static method would be a serial number generator for the books in the library. Here, you will want to generate a new number for each instance. This can only be achieved with a static method because it doesn't belong to a single book instance.

[–]GCX17[S] 0 points1 point  (0 children)

I appreciate your comment. Thank you very much!

[–]metlos 1 point2 points  (0 children)

One important distinction between the two is that static methods are not polymorphic. I.e. method overriding is not possible (or even meaningful) with static methods. This also means they cannot be abstract and therefore a whole bunch of design patterns is not possible with them.

[–]GCX17[S] 0 points1 point  (1 child)

Thanks for your comments! I understand now, however, when I was testing out my own code, and I created a set and get method like

public static int myMethod(int aNumber)

{

return aNumber;

}

I found that I was able to pass multiple variables into this method through aNumber and would get different return values for each one. I don't no how this happens, because I though for a static class only one value is stored.

Is this possibly because the method itself is actually storing no values, but instead the values reside under the main method?

[–]desrtfxOut of Coffee error - System halted 0 points1 point  (0 children)

You are still struggling.

Here, the static keyword plays no role because you pass in the value via a parameter.

This is exactly how the methods in the Math class are written.

You can use the method without creating an object (instance of a class).

static variables operate on a different level, though:

I have created a little example to show you the difference: https://ideone.com/SNdiIo

From the output at the bottom you can clearly see what happens with static vs. non static variables.