Statisches Java-Schlüsselwort (mit Beispielen)

In diesem Tutorial lernen wir anhand von Beispielen das statische Java-Schlüsselwort sowie statische Methoden, statische Variablen und statische Blöcke kennen.

Was ist ein statisches Schlüsselwort in Java?

Wenn wir in Java auf Klassenmitglieder zugreifen möchten, müssen wir zuerst eine Instanz der Klasse erstellen. Es wird jedoch Situationen geben, in denen wir auf Klassenmitglieder zugreifen möchten, ohne Variablen zu erstellen.

In diesen Situationen können wir das staticSchlüsselwort in Java verwenden. Wenn wir auf Klassenmitglieder zugreifen möchten, ohne eine Instanz der Klasse zu erstellen, müssen wir die Klassenmitglieder als statisch deklarieren.

Die MathKlasse in Java hat fast alle Mitglieder statisch. So können wir auf seine Mitglieder zugreifen, ohne Instanzen der Math-Klasse zu erstellen. Beispielsweise,

 public class Main ( public static void main( String() args ) ( // accessing the methods of the Math class System.out.println("Absolute value of -12 = " + Math.abs(-12)); System.out.println("Value of PI = " + Math.PI); System.out.println("Value of E = " + Math.E); System.out.println("2^2 = " + Math.pow(2,2)); ) )

Ausgabe :

 Absolutwert von -12 = 12 Wert von PI = 3,141592653589793 Wert von E = 2,718281828459045 2 2 = 4,0

Im obigen Beispiel haben wir keine Instanzen der MathKlasse erstellt. Aber wir können auf seine Methoden zugreifen: abs()und pow()und Variablen: PIund E.

Dies ist möglich, weil die Methoden und Variablen der MathKlasse statisch sind.

Statische Methoden

Statische Methoden werden auch als Klassenmethoden bezeichnet. Dies liegt daran, dass eine statische Methode eher zur Klasse als zum Objekt einer Klasse gehört.

Und wir können statische Methoden direkt unter Verwendung des Klassennamens aufrufen. Beispielsweise,

 class Test ( // static method inside the Test class public static void method() (… ) ) class Main ( // invoking the static method Test.method(); )

Hier können wir sehen, dass auf die statische Methode direkt von anderen Klassen unter Verwendung des Klassennamens zugegriffen werden kann.

In jedem Java-Programm haben wir die mainMethode deklariert static. Dies liegt daran, dass die JVM zum Ausführen des Programms in der Anfangsphase, in der keine Objekte im Speicher vorhanden sind, die Hauptmethode aufrufen kann.

Beispiel 1: Statische und nicht statische Java-Methoden

 class StaticTest ( // non-static method int multiply(int a, int b)( return a * b; ) // static method static int add(int a, int b)( return a + b; ) ) public class Main ( public static void main( String() args ) ( // create an instance of the StaticTest class StaticTest st = new StaticTest(); // call the nonstatic method System.out.println(" 2 * 2 = " + st.multiply(2,2)); // call the static method System.out.println(" 2 + 3 = " + StaticTest.add(2,3)); ) )

Ausgabe :

 2 * 2 = 4 2 + 3 = 5

Im obigen Programm haben wir eine nicht statische Methode mit dem Namen multiply()und eine statische Methode mit dem Namen add()innerhalb der Klasse deklariert StaticTest.

Innerhalb der Hauptklasse können wir sehen, dass wir die nicht statische Methode mit dem Objekt der Klasse ( st.multiply(2, 2)) aufrufen . Wir rufen jedoch die statische Methode unter Verwendung des Klassennamens ( StaticTest.add(2, 3)) auf.

Statische Variablen

Wenn wir in Java Objekte einer Klasse erstellen, hat jedes Objekt eine eigene Kopie aller Variablen der Klasse. Beispielsweise,

 class Test ( // regular variable int age; ) class Main ( // create instances of Test Test test1 = new Test(); Test test2 = new Test(); )

Hier haben sowohl die Objekte test1 als auch test2 separate Kopien des variablen Alters. Und sie unterscheiden sich voneinander.

Wenn wir jedoch eine Variable als statisch deklarieren, verwenden alle Objekte der Klasse dieselbe statische Variable. Dies liegt daran, dass wie statische Methoden auch statische Variablen der Klasse zugeordnet sind. Und wir müssen keine Objekte der Klasse erstellen, um auf die statischen Variablen zuzugreifen. Beispielsweise,

 class Test ( // static variable static int age; ) class Main ( // access the static variable Test.age = 20; )

Hier können wir sehen, dass wir über den Klassennamen von der anderen Klasse auf die statische Variable zugreifen.

Beispiel 2: Statische und nicht statische Java-Variablen

 class Test ( // static variable static int max = 10; // non-static variable int min = 5; ) public class Main ( public static void main(String() args) ( Test obj = new Test(); // access the non-static variable System.out.println("min + 1 = " + (obj.min + 1)); // access the static variable System.out.println("max + 1 = " + (Test.max + 1)); ) )

Ausgabe :

 min + 1 = 6 max + 1 = 11

In the above program, we have declared a non-static variable named min and a static variable named max inside the class Test.

Inside the Main class, we can see that we are calling the non-static variable using the object of the class (obj.min + 1). However, we are calling the static variable by using the class name (Test.max + 1).

Note: Static variables are rarely used in Java. Instead, the static constants are used. These static constants are defined by static final keyword and represented in uppercase. This is why some people prefer to use uppercase for static variables as well.

Access static Variables and Methods within the Class

We are accessing the static variable from another class. Hence, we have used the class name to access it. However, if we want to access the static member from inside the class, it can be accessed directly. For example,

 public class Main ( // static variable static int age; // static method static void display() ( System.out.println("Static Method"); ) public static void main(String() args) ( // access the static variable age = 30; System.out.println("Age is " + age); // access the static method display(); ) )

Output:

 Age is 30 Static Method

Here, we are able to access the static variable and method directly without using the class name. It is because static variables and methods are by default public. And, since we are accessing from the same class, we don't have to specify the class name.

Static Blocks

In Java, static blocks are used to initialize the static variables. For example,

 class Test ( // static variable static int age; // static block static ( age = 23; ) )

Here we can see that we have used a static block with the syntax:

 static ( // variable initialization )

The static block is executed only once when the class is loaded in memory. The class is loaded if either the object of the class is requested in code or the static members are requested in code.

A class can have multiple static blocks and each static block is executed in the same sequence in which they have been written in a program.

Example 3: Use of static block in java

 class Main ( // static variables static int a = 23; static int b; static int max; // static blocks static ( System.out.println("First Static block."); b = a * 4; ) static ( System.out.println("Second Static block."); max = 30; ) // static method static void display() ( System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("max = " + max); ) public static void main(String args()) ( // calling the static method display(); ) )

Output:

 First Static block. Second Static block. a = 23 b = 92 max = 30

In the above program. as soon as the Main class is loaded,

  • The value of a is set to 23.
  • The first static block is executed. Hence, the string First Static block is printed and the value of b is set to a * 4.
  • The second static block is executed. Hence, the string Second Static block is printed and the value of max is set to 30.
  • Und schließlich werden die print-Anweisungen innerhalb der Methode display()ausgeführt.

Verschachtelte statische Klasse

In Java können wir eine Klasse innerhalb einer anderen Klasse deklarieren. Solche Klassen werden als verschachtelte Klassen bezeichnet. Es gibt zwei Arten verschachtelter Klassen:

  • Statisch verschachtelte Klassen
  • Nicht statische verschachtelte Klassen

Beispielsweise,

 class OuterClass ( // static nested class static class NestedClass (… ) // non-static nested class class InnerClass (… ) )

Weitere Informationen finden Sie in der Java Nested Class.

Interessante Beiträge...