Path Menu Get Unstuck Tools: My Home
Path Menu Get Unstuck Tools: My Home
Path Menu
Workspace restored.
Get Unstuck
Tools
Learn
LEARN JAVA: METHODS
Scope
A method is a task that an object of a class performs.
We mark the domain of this task using curly braces: {, and }. Everything inside the curly braces
is part of the task. This domain is called the scope of a method.
We can’t access variables that are declared inside a method in code that is outside the scope of
that method.
class Car {
String color;
int milesDriven;
However, milesDriven, which is declared at the top of the class, can be used inside all methods in
the class, since it is in the scope of the whole class.
Instructions
1.
Inside of the advertise() method, change the productType variable to the cookie variable, which
is declared in the main() method. This should also result in the printout:
Selling cookies!
Right?
Checkpoint 2 Passed
Hint
Your advertise() method should now look like:
Hint
Your advertise() method should now look like it did at first:
Selling Cookies!
Right?
Checkpoint 4 Passed
Hint
Your main() method should now look something like:
public static void main(String[] args) {
String cookie = "Cookies";
Store cookieShop = new Store(cookie);
cookieShop.advertise();
System.out.println(message);
}
However, you’ll see that this code won’t work, since message is not defined in the main() method.
That’s okay! It’s helpful to see the error, so that you can better understand how it looks when
you call a variable outside of its scope.
4.
Foiled again! The message variable only exists inside the scope of the advertise() method!
Hint
Your main() method should now look like it did on at first:
cookieShop.advertise();
}
public class Store {
// instance fields
String productType;
// constructor method
productType = product;
// advertise method
System.out.println(message);
}
// main method
cookieShop.advertise();