Lesson 9 - Static class members in Java
In the previous lesson, Arena with a mage in Java (inheritance and polymorphism), we put our knowledge of inheritance and polymorphism to the test. In today's tutorial, we're going to go over static class members in Java. Until now, we only used data, states, being carried by an instance. Fields, which we've defined, belonged to an instance and were unique to each instance. OOP, however, allows us to declare fields and methods on a class itself. We call these members static, sometimes called class members, who are independent of an instance.
WARNING! Today's lesson will show you that static members are approaches that actually violate the object-oriented principles. OOP includes them only for special cases and in general everything can be written without static members. We always have to think carefully before adding static members. Generally, I would recommend for you not to use static members ever, unless you're absolutely sure what you're doing. Like global variables, which Java, fortunately, doesn't have, static members are something that enable you to write bad code and violate good practices. Today, we'll go over this topic just to make you understand some static methods and classes in Java libraries, not to write your own. Use this knowledge wisely, there will be less evil in the world.
Static (class) fields
We can declare various elements as static, let's start with fields. As I mentioned in the introduction, static elements belong to a class, not to an instance. So the data stored there can be read even if an instance of the class has not been declared. Basically, we could say that static fields are shared among all class instances, but even that wouldn't be accurate since they aren't actually related to instances. Let's create a new project, name it something like Statics, and create a simple User class:
public class User { private String name; private String password; private boolean loggedIn; public User(String name, String password) { this.name = name; this.password = password; loggedIn = false; } public boolean logIn(String enteredPassword) { if (enteredPassword.equals(password)) { loggedIn = true; return true; } else { return false; // wrong password } } }
The class is simple, it represents a user in a system. Each user instance has its own name, password, and carries information about whether the user is logged in. In order for the user to log-in, we call the logIn() method which takes a password as a parameter. The method verifies whether it's the right password. If the person behind the keyboard is really that user, it logs him/her in. It returns true/false depending on whether the login was successful. In reality, the password would be also hashed, but we won't do any hashing this time around.
When a new user registers, the system tells him/her what the minimum length of their password must be. This number should be stored somewhere. During user registration, we still wouldn't have its instance. The object has not been created and would only be created after the form has been completely filled and submitted. Therefore, we can't use a public minimalPasswordLength field in the User class for this purpose. Either way, we still need a minimum password length stored in the User class somewhere since it, naturally, belongs there. We'll make this value a static field using the static modifier:
public class User { private String name; private String password; private boolean loggedIn; public static int minimalPasswordLength = 6; ... }
Now, let's switch to Statics.java and print the field to the console. We access this field directly on the class:
{JAVA_OOP}
public class User {
private String name;
private String password;
private boolean loggedIn;
public static int minimalPasswordLength = 6;
public User(String name, String password) {
this.name = name;
this.password = password;
loggedIn = false;
}
public boolean logIn(String enteredPassword) {
if (enteredPassword.equals(password)) {
loggedIn = true;
return true;
} else {
return false; // wrong password
}
}
}
{JAVA_MAIN_BLOCK}
System.out.println(User.minimalPasswordLength);
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
We can see the field really belongs to the class. We can access it from different places in the code without having to create a user. On the contrary, we wouldn't be able to access it on the user instance:
User u = new User("Thomas White", "passwordissword"); System.out.println(u.minimalPasswordLength); // this line causes an error
NetBeans will report an error and the code won't be compiled.
Another practical use of static fields is to assign unique identification numbers to each user. If we didn't know what static members were, we'd have to check every user creation and increment a counter. Instead, we'll create a private static field nextId right on the User class. The next user who registers will have their id stored there. The first user's id will be 1, the second 2, and so on. The User will get a new attribute - id, that will be set in the constructor depending on what the nextId value is:
public class User { private String name; private String password; private boolean loggedIn; private int id; public static int minimalPasswordLength = 6; private static int nextId = 1; public User(String name, String password) { this.name = name; this.password = password; loggedIn = false; id = nextId; nextId++; } ... }
The class stores the next instance's id by itself. We assign this id to a new instance in the constructor and increase it by 1, which prepares it for the next instance. Not only fields can be static, this approach could be applied to a variety of class members.
Static methods
Static methods are called on the class. All they usually are is utilities that we need to use often and creating an instance every time would be counterproductive. Java implicitly uses static members. Have you noticed how we never have to create a System class instance in order to write something to the console? The System.out.println() method on the out attribute is static, as the attribute itself. We're only allowed to run one System at a time, so it would be pointless to create an instance every time we wanted to use it. We've already experienced a similar situation with the round() method in the Math class. It would be pointless to instantiate a Math class to do such a simple thing as rounding. Static methods are generally just there to help us where the instantiation is counterproductive or makes no sense at all.
Let's make another example, just to clarify. During user registration, we need to know the minimum password length before we create its instance. Also, it would be great if we could check the password before the program creates the user. A full check, in this case, would include checking whether the length is correct, making sure it doesn't contain accent characters, verifying that there is at least one number in it, and so on. To do this, we'll create a static validatePassword() method:
public static boolean validatePassword(String password) { if (password.length() >= minimalPasswordLength) { // password validation code (omitted for simplification purposes) return true; } return false; }
We'll call this method on the User class:
{JAVA_OOP}
public class User {
private String name;
private String password;
private boolean loggedIn;
private int id;
public static int minimalPasswordLength = 6;
private static int nextId = 1;
public User(String name, String password) {
this.name = name;
this.password = password;
loggedIn = false;
id = nextId;
nextId++;
}
public boolean logIn(String enteredPassword) {
if (enteredPassword.equals(password)) {
loggedIn = true;
return true;
}
else
return false; // wrong password
}
public static boolean validatePassword(String password) {
if (password.length() >= minimalPasswordLength) {
// password validation code (omitted for simplification purposes)
return true;
}
return false;
}
}
{JAVA_MAIN_BLOCK}
System.out.println(User.validatePassword("passwordissword"));
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
Viewer beware! The validatePassword() method belongs to the class. Meaning that we can't access any instance fields in it. Those fields don't exist in the class context, rather in the context of an instance. It wouldn't make any sense to use the user's name in our method! You can try it out if you'd like to get a visual confirmation of its impossibility.
Password validation can be achieved without knowledge of static members. We could create a UserValidator class and write methods in it accordingly. Then, we'd have to create its instance to be able to call those methods. It'd be a bit confusing because the "concept of a user" would be unnecessarily split up into two classes. Now, thanks to static members, all of the information is neatly organized in one place.
Thinking back, we really don't want the minimalPasswordLength static attribute to be accessible from outside the class. What we'll do is make it private and create a static get method for reading. We know this approach well from previous lessons. Let's add the get method that retries both the minimum password length and the instance's id:
public static int getMinimalPasswordLength() { return minimalPasswordLength; } public int getId() { return id; }
Statics.java should look something like this now:
{JAVA_OOP}
public class User {
private String name;
private String password;
private boolean loggedIn;
private int id;
private static int minimalPasswordLength = 6;
private static int nextId = 1;
public User(String name, String password) {
this.name = name;
this.password = password;
loggedIn = false;
id = nextId;
nextId++;
}
public boolean logIn(String enteredPassword) {
if (enteredPassword.equals(password)) {
loggedIn = true;
return true;
} else {
return false; // wrong password
}
}
public static boolean validatePassword(String password) {
if (password.length() >= minimalPasswordLength) {
// password validation code (omitted for simplification purposes)
return true;
}
return false;
}
public static int getMinimalPasswordLength() {
return minimalPasswordLength;
}
public int getId() {
return id;
}
}
{JAVA_MAIN_BLOCK}
User u = new User("Thomas White", "passwordissword");
System.out.println("First user's ID: " + u.getId());
User v = new User("Oli Pickle", "csfd1fg");
System.out.println("Second user's ID: " + v.getId());
System.out.println("Minimum password length: " + User.getMinimalPasswordLength());
System.out.println("Password validation \"password\": " + User.validatePassword("password"));
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
The output will be:
Console application
First user's ID: 1
Second user's ID: 2
Minimum password length: 6
Password validation "password": true
Note that even the main() method is static since we are only allowed to run one program at a time. Meaning that we're only able to call static methods from the default main class from within the main() method. Now you know how to add such methods directly to Statics.java, but it doesn't make much sense to use this approach since the application logic should take place in encapsulated objects.
Static constructor
The class could also have a static constructor. A static constructor is called when the application starts and the class is being registered for use. It can be used for initialization, calculations and so on. Similarly to instance constructors, we are able to create instances of classes and store them into static fields in static constructors.
Private constructor
If a class contains only utility methods or it doesn't make sense to create an instance of it, for example we'll never run two consoles at a time, we can declare its instance constructor as private. Keep in mind, we can't instantiate such a class (create its instances). A similar class that we're already familiar with is Math. Let's attempt to create an instance of the Math class:
Math m = new Math(); // this code causes error
NetBeans will report an error. Static classes have all their members set to static, so it wouldn't make any sense to create an instance of it because the result would be an empty object.
Static registry
Let's create a simple static class. We could create a class containing only utility methods and fields, e.g. Math. However, I've decided I'll have us create a static registry. Which is basically how you share important data between classes without making an instance.
Let's say we're making a more robust application, e.g. a digital journal. The application would be multilingual, its features would include adding bookmarks, choosing folders for storing files, color schemes and even running at system startup. It would have adjustable settings, e.g. picking the first day of the week (Sunday/Monday), which would be accessed from various parts in the code. Without knowledge of static members, we'd have to pass the settings instance to all objects (calendar, tasks, notes...) through the constructor.
One workaround would be to use a static class to store these settings. It would be accessible everywhere in the program, without even having to create an instance. It would contain all the necessary settings that would be used by objects. Our static class would end up looking something like this:
public class Settings { private static String language = "ENG"; private static String colorScheme = "red"; private static boolean runAtStartUp = true; public static String language() { return language; } public static String colorScheme() { return colorScheme; } public static boolean runAtStartUp() { return runAtStartUp; } }
All fields and methods must be declared with the static modifier, also notice the private constructor. I purposely didn't use the public class fields, and made get methods instead, so the values wouldn't be able to be changed. Which is still a bit uncomfortable from a programmer's point of view. Next time we'll learn how to go about doing this in a more efficient way.
Now we'll put our class to use even though we don't have a full journal application. Let's make a Calendar class and verify that we can truly access the Settings there. We'll add a method to it that returns all of the settings:
public class Calendar { public String getSettings() { String s = ""; s += "Language: " + Settings.language() + "\n"; s += "Color scheme: " + Settings.colorScheme() + "\n"; s += "Run at start-up: " + Settings.runAtStartUp() + "\n"; return s; } }
Last of all, print it all to the console:
{JAVA_OOP}
public class Settings {
private static String language = "ENG";
private static String colorScheme = "red";
private static boolean runAtStartUp = true;
public static String language() {
return language;
}
public static String colorScheme() {
return colorScheme;
}
public static boolean runAtStartUp() {
return runAtStartUp;
}
}
public class Calendar {
public String getSettings() {
String s = "";
s += "Language: " + Settings.language() + "\n";
s += "Color scheme: " + Settings.colorScheme() + "\n";
s += "Run at start-up: " + Settings.runAtStartUp() + "\n";
return s;
}
}
{JAVA_MAIN_BLOCK}
Calendar calendar = new Calendar();
System.out.println(calendar.getSettings());
{/JAVA_MAIN_BLOCK}
{/JAVA_OOP}
The output:
Console application
Language: ENG
Color scheme: red
Run at start-up: true
We see that calendar instance has no problem accessing all program settings.
Again, be careful, this code can be improperly used to share unencapsulated data. We must only use it in specific situations. Most data exchanges should happen using parameterized instance constructors, not through static members.
Static members appear very often in design patterns, we've already mentioned them in our lessons. We'll get in further detail in the approaches that bring object-oriented programming to perfection later on. For now, this will do. I don't want to overwhelm you In the next lesson, Solved tasks for OOP in Java lesson 9, we'll look at what properties are in Java.
In the following exercise, Solved tasks for OOP in Java lesson 9, we're gonna practice our knowledge from previous lessons.