Java programming course: 5.1 Static members, constants, and conditionals

In the previous lesson we started to manage the zoo using class ZooAdministrator.


Static members, constants, and conditionals

The static keyword enables you to define a variable or method that is not dependent upon any object. A constant is a variable whose value cannot be changed after it has been initialised. Conditional statements allow you to control when certain parts of your code are executed depending on whether a certain condition is met. Casting refers to the process of converting between compatible types.

In this section you will learn:

  • How to use static members
  • How to define constants
  • How to write conditional code
  • What casting is and how to use it

Static variables and methods

Sometimes it is useful to have a variable and/or method that is not associated with any instance of a class, either because it makes sense to "share" it among all instances or because it doesn't require an instance for its existence.

Suppose you want to keep a count of the combined age of all of the animals in the zoo. You could either calculate this externally to the Animal class or make it an integral facility of the class itself. The latter approach can be achieved by defining a static variable inside Animal which will be called combinedAge. Static variables are also known as class variables because they relate to the class as whole rather than to any particular instance.

It is common to declare static variables before the instance variables, so insert the statements below marked:

public abstract class Animal {

    // Static variables
    private static int combinedAge;
    
    // Declare instance variables to hold an animal's attributes
    .. rest of code ommitted ..
 

Note the following:

  • The combinedAge variable is defined as static meaning it is "shared" among all instances, and there need not even be any instances: the variable will still exist
  • It is defined as private to prevent other objects outside of this class from gaining direct access to it
  • Because it declared to be the primitive type int its default value will be zero

You should now insert a line at the end of the constructor to add the age of the animal in the process of being created to the value of the static variable named combinedAge:

public Animal(String name, String gender, int age) {
    this.name = name;
    this.gender = gender;
    this.age = age;
    dateAdmitted = new Date(); // today's date is assumed
        
    // Add this animal's age to the combined age total
    combinedAge = combinedAge + this.age;
}
 

Each instance, both within constructors and methods, has access to its static variables

The value of combinedAge is added to this.age to obtain a new total. This new total is then stored back inside variable combinedAge

There is a short-cut technique which can be used to add the age into the total, so you could replace the statement to be as follows:

combinedAge += this.age; 

Because the variable is private you need to define a public getter method, which in this case you will call getCombinedAge():

// Static methods
public static int getCombinedAge() {
    return combinedAge;
}
 

The method is defined using the static keyword because it makes use of a static variable. In fact, instance methods can also make use of static variables, so the method does not have to be marked as static. However, making it static has the benefit that client objects can invoke the method without needing to create any Animal object first, as you will see shortly.

To reference the method in other objects you should prefix the method name with the name of the class the method exits within. Define the following code in the main() method of Experiments:

// At this point no animals have been created
System.out.println("Combined age = " + Animal.getCombinedAge());
        
// Now create an animal aged 3
Animal leo = new Lion("Leo", "m", 3);
System.out.println("Combined age = " + Animal.getCombinedAge());
        
// Create another animal aged 4
Animal bonzo = new Monkey("Bonzo", "m", 4);
System.out.println("Combined age = " + Animal.getCombinedAge());
 

To run the code in class Experiments you need to right-click on the Experiments.java node in the Projects window and select Run. This is because this class is not the default class of the project (VirtualZoo is), so you need to select the specific class that contains a main() method to execute.

The above code outputs the combined age value before any animals are created, and then again after the first and then second animals are created. You should see the following in the Output window:

Combined age = 0
Combined age = 3
Combined age = 7
 

Note the following:

  • The combinedAge variable exists even before an instance is created
  • You prefixed the method call with the name of the class: Animal.getCombinedAge().

As you can see, it is possible to invoke class methods even before any instances exist. If you do have an instance, the syntax rules of Java allow you to use the name of the instance instead of the class name as the prefix (e.g., leo.getCombinedAge()) but this is strongly discouraged since it implies that it is an instance method rather than a class method.


In the next lesson we will explain the syntax of System.out.println().

Next lesson: 5.2 Understanding System.our.println


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image