Sie sind auf Seite 1von 4

Class Attributes

Sometimes it is desirable to have a variable that is shared among


all instances of a class. For example, this can be used as the
basis for communication between instances or to keep track of
the number of instances that have been created.
You achieve this effect by marking the variable with the
keyword static. Such a variable is sometimes called a class
variable to distinguish it from a member or instance variable,
which is not shared.

1 public class Count {


2 private int serialNumber;
3 public static int counter = 0;
4
5 public Count() {
6 counter++;
7 serialNumber = counter;
8 }
9 }
 A static variable is similar in some ways to a global
variable in other languages.
Class Methods
Sometimes you need to access program code when you do not
have an instance of a particular object available. A method that
is marked using the keyword static can be used in this way
and is sometimes called a class method.
1 public class Count {
2 private int serialNumber;
3 private static int counter = 0;
4
5 public static int getTotalCount() {
6 return counter;
7 }
8
9 public Count() {
10 counter++;
11 serialNumber = counter;
12 }
13 }
You should access methods that are static using the class name
rather than an object reference, as follows:
1 public class TestCounter {
2 public static void main(String[] args) {
3 System.out.println("Number of counter is
"
4 + Count.getTotalCount());
5 Count count1 = new Count();
6 System.out.println("Number of counter is
"
7 + Count.getTotalCount());
8 }
9 }
The output of the TestCounter program is:
Number of counter is 0
Number of counter is 1
Because you can invoke a static method without any
instance of the class to which it belongs, there is no this
value. The consequence is that a static method cannot
access any variables apart from the local variables, static
attributes, and its parameters. Attempting to access non-static
attributes causes a compiler error.
Note – Non-static attributes are bound to an instance and
can be accessed only through instance references.
1 public class Count {
2 private int serialNumber;
3 private static int counter = 0;
4
5 public static int getSerialNumber() {
6 return serialNumber; // COMPILER ERROR!
7 }
8 }
Important points to remember about static methods are:
 A static method cannot be overridden.
 main() is static because the JVM does not create an
instance of the class when executing the main method. So
if you have member data, you must create an object to
access it.
Different static blocks within a class are executed in the order of
their appearance in the class.
1 public class Count {
2 public static int counter;
3 static {
4 counter =6;
5 }
6 }
7
8 public class TestStaticInit {
9 public static void main(String[] args) {
10 System.out.println("counter = "+
Count.counter);
11 }
12 }

Das könnte Ihnen auch gefallen