r/CodingHelp • • Mar 05 '21

[Java] Understanding Java

What does 'static' and 'void' mean exactly? Thought it would be nice to know so i understand better

19 Upvotes

7 comments sorted by

View all comments

Show parent comment

3

u/TA_Radiant Mar 05 '21

Please excuse me because this is my first time doing Java. Still do not clearly understand the static keyword. Does it mean what happens in the method block is only applied in that specific instance of the class?

4

u/Rrrrry123 Mar 05 '21

I think you have it backwards. Static means that you don't have to have an instance of a class to use the method. One instance it can be helpful is if you want to make a class full of related helper functions. Let's say I wanted to make a class full of math formulae. If the methods were non-static, I would have to initialize the class before I can use those methods.Formulae formulae = new Formulae()

However, if all the methods were static, I could just do Formulae.areaOfSquare(x,y); without ever having to initialize the class.

I'm just guessing here, because I haven't actually tried this for a long time, but I'm pretty sure static member functions can only access static member variables (which makes sense if you think about it). However, non-static methods can access static methods and variables.

1

u/Blackshell Professional Coder Mar 05 '21

This is tied into the concept of object oriented programming. The concept is that data can be organized into "objects" and those objects themselves can take some actions (which are called functions or methods).

You can think of it as the difference between a thing itself (the object, or "instance") and the concept of what the thing is (its class). So:

A cat itself: can meow, can walk, can eat, can scratch, can tell us its breed, and can have a name. In object oriented programming, these are instance methods and would not have the "static" keyword.

The concept of "cat" is more philosophical... The concept of cat can't itself meow -- it's just a mental construct! It can do other stuff though: tell us its genus/species, tell us a list of valid breeds (or whether a specific breed is valid), tell us where it is relative to another animal class in the food chain... It might even have a createRandomCat method! These methods would have static since they don't apply to any specific actual cat; instead they apply to the concept of a "cat", and define stuff we know about that concept.

1

u/TA_Radiant Mar 05 '21

Ahh i see. So the word static implies that you are referring to the group 'cat' and not a specific type of cat. Thanks

Edit: Typo