The static modifier can be used for:
- variable
for example type: int
2. methods
for example void method
static void nameOfMethod () {
}
3. block
static{System.out.println("hoi");}
4.nested classes
for example class with default modifier
static class nameOfClass {
}
The static modifier will link the variable, method, block or nested class to its class. This means that you could call the variable/method/block/nested class (which is made static) from another class by only calling the class its name. So you don’t have to make a new object.
So, if you have 2 classes:
//normally do you create classes in different tabs, but you could also do them in one, this is just for the example.
package P;
import java.io.PrintStream;
class Class1 {
PrintStream out;
Class1() {
out = new PrintStream(System.out);
void start(){
}
public static void main(String[] argv) {
new Class1().start();
}
}
class Class2 {
int i = 5;
}
This is an example when you use the static modifier for variables. But it will work the same for the others.
So normally you create an object:
Object objectName = new Object();
and then do you write:
Object objectName = new Object();
objectName.i = 5;
So you program looks like this:
package P;
import java.io.PrintStream;
class Class1 {
PrintStream out;
Class1() {
out = new PrintStream(System.out);
void start(){
Class2 number = new Class2();
out.print(number.i);
}
public static void main(String[] argv) {
new Class1().start();
}
}
class Class2 {
int i = 5;
}
When you use the word static you don’t have to create a new object. You just have to implement in the void start():
Then you whole code looks like this:
package P;
import java.io.PrintStream;
class Class1 {
PrintStream out;
Class1() {
out = new PrintStream(System.out);
void start(){
out.print(Class2.i);
}
public static void main(String[] argv) {
new Class1().start();
}
}
class Class2 {
static int i = 5;
}
output:
5