The difference between class variables
and instance
variables, is simply a question of who knows what?
.
An instance variable
is only known (= bound) to that concrete instance - hence the name.
public class Person {
private String firstName;
private String lastName;
[...]
}
The definition of a class is like a blueprint for building concrete objects. Perhaps this point confuses you a bit. But writing it this way, every variable would be bound to its concrete object: e.g. Every person has its own firstName
A class variable
on the other hand is - as the name says - known to each and every member of a class; or technically: It is known/ bound at class level. The typical example is a counter of how many objects, you have created - although it is a very problematic example; but that doesn't matter at this early stage.
public class Person {
private String firstName;
private String lastName;
[...]
static int numberOfPersons = 0
}
numberOfPersons
is declared static
which is the keyword to distingush between class variables
and instance variabes
. The variable is declared like the others within the class definition. But the static
keyword signals, that it is different.
firstName
, lastName
are instance variables and bound to that concrete instance
numberOfPersons
is bound to the class, so that every instance could access this variable.
tl;dr
The place where variables are defined is the class definition.
Class variables are known at/bound to the class level, i.e. each concrete instance has access to it. To define a class variable, you use the keyword static
.
Instance variables are only known at an instance level. You define them without the static
keyword.
Further documentation for Java is here