In Unit 1, we learned about methods by using the Math class and its many static methods like Math.random(), and we wrote our own main methods and other methods that were static. These are called class methods because they belong to the class and not to any object of the class. In this lesson, you will learn to write your own class variables and methods using the keyword static and compare them to instance variables and methods.
In lessons 1.9 and 1.10, we learned how to call class methods (also called static methods). Class methods are called using the class name followed by the dot (.) operator and the method name, example, Math.sqrt(25); calls the sqrt method in the Math class to find the square root of 25. Class methods use the keyword static in their method signature. They do not access or change the attributes of an object.
In this lesson, we will learn more about instance methods which are always called using an object of the class. They are not static methods. They access and change the attributes of the object they are called on, for example yertle.forward() changes the Turtle object yertleβs position.
The following flowchart shows the difference between calling class (static) methods and instance methods. Static methods are called using the class name, for example, Math.sqrt(25);. Instance methods are called using an object of the class, for example, yertle.forward();. Traditionally, class names are capitalized, and object variables are lowercase.
Class methods belong to the class and not to any object of the class. They are called with the class name and the dot operator, like ClassName.methodName();, for example the Math methods like Math.random();. There is only one copy of a class variable or method for the whole class. For example, the main method is a class (static) method because there should only be 1 main method. If the method is in the same class, you can call it with or without the class name from other static methods in the class: Classname.methodName(); or staticMethodName(); or even with an object of the class: objectName.methodName();.
// Calling class methods
// ClassName.methodName();
int x = Math.sqrt(9);
// If the method is in the same class,
// you can call it with or without the class name
// from other static methods in the class
ClassName.methodName();
methodName();
Letβs revisit the following flowchart to compare three different ways of calling methods. Class (static) methods are called using the class name. Instance methods can only be called using an object of the class. If you are calling the instance method from the main method or from another class, you must first create an object of that class and then call its methods using object.methodName(). If you are calling the method from within the same class, you can just call the method using methodName() which will refer to the current object.
When writing class methods, they can be public or private. The static keyword is placed right after the public/private modifier and right before the type of variables and methods in their declarations.
public class ClassName
{
// static class variable
public static type variableName;
// static class method
public static returnType methodName(parameters)
{
// implementation not shown
}
}
Class (static) methods can access or change the values of class (static) variables and can call other class (static) methods. However, they cannot access or change the values of (non-static) instance variables or call (nont-static) instance methods without being passed an instance of the class via a parameter. For example, the main method which is static can call other static methods directly with or without the classname, but it cannot call instance methods without first creating an object. Try this below to see βnon-static variable or method cannot be referenced from a static contextβ errors.
Note that the static method printStatic has errors in it because it cannot access the instance variables and methods. Fix the printStatic method by giving it the Person object as a parameter and using this object to call its instance variables and methods. Also fix the method call to printStatic in main to pass in the object as an argument.
This example also shows how instance methods easily share data variables without the need for parameters. Whereas, static methods cannot directly access the instance methods. They are often used for utility methods, like Math operations, that do not need access to the instance variables of an object.
Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type. Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.
In the following class Person, there is a static variable called personCounter that is incremented each time the Person constructor is called to initialize a new Person object. The static method printCounter prints out its value. You can also watch how it works in the Java visualizerβ1β
public class Temperature {
private double temperature;
public static double maxTemp = 0;
public Temperature(double t) {
temperature = t;
if (t > maxTemp) {
maxTemp = t;
}
}
public static void main(String[] args) {
Temperature t1 = new Temperature(75);
Temperature t2 = new Temperature(100);
Temperature t3 = new Temperature(65);
System.out.println("Max Temp: " + Temperature.maxTemp);
}
}
The keyword final can be used in front of a variable declaration to make it a constant value that cannot be modified. Constants are traditionally capitalized.
Try the following code and notice the syntax error when we try to change the constant PI. Put the comment symbols // in front of that line to remove the error and run it again.
Verse 1:
The ants go marching one by one, hurrah, hurrah
The ants go marching one by one, hurrah, hurrah
The ants go marching one by one
The little one stops to suck a thumb
And they all go marching down to the ground
To get out of the rain, BOOM! BOOM! BOOM! BOOM!
Verse 2:
The ants go marching two by two, hurrah, hurrah
The ants go marching two by two, hurrah, hurrah
The ants go marching two by two
The little one stops to tie a shoe
And they all go marching down to the ground
To get out of the rain, BOOM! BOOM! BOOM! BOOM!
Verse 3:
The ants go marching three by three, hurrah, hurrah
The ants go marching three by three, hurrah, hurrah
The ants go marching three by three
The little one stops to climb a tree
And they all go marching down to the ground
To get out of the rain, BOOM! BOOM! BOOM! BOOM!
Letβs create a class to print out the song with 2 methods chorus() and verse, where the verse takes 2 parameters for the numbers and the action. Notice that this is a class where there are no instance variables and we donβt really need to generate multiple objects. With students or pets, it makes sense to have multiple objects. With a class printing out a song, we can just make the methods static and have just 1 copy of them.
Create a class called Song with two static methods: chorus() and verse(). The chorus method prints out the last two lines of each verse. The verse method takes two parameters, a number and an action, and prints out the verse with the number and action.
Add a public static variable called numVerses to the class that keeps track of the number of verses. Increment this variable in the method verse and print it out at the beginning of the verse.
Song using two static methods: chorus() and verse(). The chorus method should print out the last two lines of each verse. The verse method should take two parameters, a number and an action, and print out the verse with the number and action. Add a public static variable called numVerses that keeps track of the number of verses. Increment this variable in the method verse and print it out at the beginning of the verse.
(AP 3.7.A.1) Class methods cannot access or change the values of instance variables or call instance methods without being passed an instance of the class via a parameter.
(AP 3.7.B.1) Class variables belong to the class, with all objects of a class sharing a single copy of the class variable. Class variables are designated with the static keyword before the variable type.
(AP 3.7.B.2) Class variables that are designated public are accessed outside of the class by using the class name and the dot operator, since they are associated with a class, not objects of a class.