Static Classes
The other type of class is a static class, these methods can't be created into objects. Instead their methods and fields are called directly from the class. Along with this, since they don't come in the form of objects, they don't have constructors.
Making a static class
When making a static class, you have to add the static identifier to both the class declaration, methods, and all fields (not variables that are in a method).
Here is an example of a static class:
public static class ExampleStaticClass{
//feilds
public static int x = 3;
public static int y = 4;
//methods
public static int add1ToY(){
this.y++;
return this.y
}
public static int add1ToX(){
this.x++;
return this.x;
}
}
Calling static classes
When it comes to calling methods or fields from a static, you don't create a method like in an instance class, you instead call it directly from the class by the name.
Here is an example using the static
class ExampleStaticClass
:
int val = ExampleStaticClass.y; //get int from y
//add 1 to y and return new value
int newVal = ExampleStaticClass.add1ToY();
System.out.println("Difference: " + (newVal - val) );
Last updated