The scope of a variable is defined as where a variable is accessible or can be used. The scope is determined by where you declare the variable when you write your programs. When you declare a variable, look for the closest enclosing curly braces ({}) β this is its scope.
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 by clicking the CodeLens button below.
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.
Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared. Local variables that are declared inside a method are usually declared at the top of the method. These variables can only be used within the method and do not exist outside of the method.
Parameter variables are also considered local variables that only exist for that method or constructor. These variables may only be used within the constructor or method and cannot be declared to be public or private.Itβs good practice to declare any variables that are used by just one method as local variables in that method.
Instance variables at class scope are shared by all the methods in the class and can be marked as public or private with respect to their access outside of the class. They have class scope regardless of whether they are public or private.
Another way to look at scope is that a variableβs scope is where it lives and exists. You cannot use the variable in code outside of its scope. The variable does not exist outside of its scope.
Try the following code to see that you cannot access the variables outside of their scope levels in the toString() method. Explain to someone sitting next to you why you canβt access these. Try to fix the errors by either using variables that are in scope or moving the variable declarations so that the variables have larger scope.
If there is a local variable with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable, as seen below. Weβll see in the next lesson, that we can distinguish between the local variable and the instance variable using the keyword this to refer to this objectβs instance variables.
In this example, the local variable is used instead of the instance variable of the same name. What will the code print out? Try it with the CodeLens button.
Debug the following program that has scope violations. You may need to add methods or use methods that are in the class Fraction appropriately. Then, add comments that label the variable declarations as class, method, or block scope.
Subsection9.3.8Coding Challenge: Static Song and counter
In SectionΒ 3.1Β Writing methods, we wrote a class with methods to print out the song The Ants Go Marching. Hereβs the song with three verses, where the chorus is the last two lines of each verse:
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 two methods chorus() and verse, where the verse takes two 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 one 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.
This class should print out the The Ants Go Marching 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.
(AP 3.8.A.1) Local variables are variables declared in the headers or bodies of blocks of code. Local variables can only be accessed in the block in which they are declared.
(AP 3.8.A.1) Parameters to constructors or methods are also considered local variables. These variables may only be used within the constructor or method and cannot be declared to be public or private.
(AP 3.8.A.2) When there is a local variable or parameter with the same name as an instance variable, the variable name will refer to the local variable instead of the instance variable within the body of the constructor or method.
public class Party {
private int boxesOfFood;
private int numOfPeople;
public Party(int people, int foodBoxes) {
numOfPeople = people;
boxesOfFood = foodBoxes;
}
public void orderMoreFood(int additionalFoodBoxes) {
int updatedAmountOfFood = boxesOfFood + additionalFoodBoxes;
boxesOfFood = updatedAmountOfFood;
}
public void eatFoodBoxes(int eatenBoxes) {
boxesOfFood = updatedAmountOfFood - eatenBoxes;
}
}
public class Movie {
private int currentPrice;
private int movieRating;
public Movie(int p, int r) {
currentPrice = p;
movieRating = r;
}
public int getCurrentPrice() {
int currentPrice = 16;
return currentPrice;
}
public void printPrice() {
System.out.println(getCurrentPrice());
}
}
Which of the following reasons explains why the printPrice method is βbrokenβ and only ever prints out a value of 16?
currentPrice is declared as a local variable in the getCurrentPrice method and set to 16, and will be used instead of the instance variable currentPrice.