A key concept in java is the idea of instantiation. A class definition has all the rules for one type of object. Each instance of the object will follow the same rules. For example, if I define
class Ball {
public void bounce() {
// lots of code here
}
}
Then the system has code for things called Ball
s which can bounce
If I want two balls...
public class Main {
public static void main(String args[]) {
Ball beachBall = new Ball();
Ball soccerBall = new Ball();
and I can bounce them all I want
beachBall.bounce();
beachBall.bounce();
soccerBall.bounce();
beachBall.bounce();
but I cannot say
Ball.bounce();
because that leaves my system with the question "Which ball?"
static
methods and variables are not associated with specific instances.
For example:
class Werewolf {
static boolean fullMoon = false;
static void setFullMoon(boolean isVisible) {
fullMoon = isVisible;
// code code code
}
void eatPerson(Person p) {
// code code code
}
}
The static method applied to all werewolves so it is called on the class:
Werewolf.fullMoon(true);
The non-static (instance) method applied to a particular werewolf so it is called on an instance.
jeff.eatPerson(chuck);
Jeff is the werewolf. Chuck is the person he eats.
Try to ignore the cruel comments. We all started somewhere.