- Objects
- Classes
- Inheritance
-
Programming in Java on Your Computer - Classes and Objects in BlueJ
- Trying out Code in BlueJ
- The Code for Creating and Using Objects
- Source Code and Methods
- Accessors and Mutators
- Constructor Code
- Scope
- Inheritance
-
BlueJ Review - Class Code
- Simple Debugging
- Interactive Picture
- Refactoring Code with Inheritance
Scope
Premium Content - Free Preview
As mentioned in Accessors and Modifiers, some variables are only available within a certain method, while other variables are available to all of the code in the Class.
The area of code that a variable is available to, is known as the scope. A scope (or "block") is normally specified by curly-braces in Java. BlueJ marks the different scopes with different colors, so you can see them more clearly:
You can view the different levels of scope as different colors, from the Class to the Methods to the Loops within methods. (The code editor on this site does not mark scopes with colors, but it does put little arrows on the side for collapsing and expanding them.)
Any variable declared in a specific scope is available only to that scope (except for non-private instance variables). Code outside of that scope cannot access that variable. In fact, the variable gets deleted once its scope of code finishes running.
End of Free Content Preview. Please Sign in or Sign up to buy premium content.
Comments
Victoria Holland
Jan 17, 7:12 AMI have the correct answer now, but first of all I thought it would be 16. I didn't think the call to the doubleTotal method would actually change the value of the total variable, because the method is void and the new total doesn't get returned as an integer.
calo
Jan 26, 2:24 PMHow it works then with void? It only do something there, change the value, but type for total is taken from the beginning of the class, when int total; is defined <
Learneroo
Jan 26, 2:40 PMtotal
is available to the whole instance, sodoubleTotal
will double it for all the code that uses it. In general, variables are available to the entire scope (marked with{}
) that they are declared in.Declare a variable in a loop? available to that loop. Declare it in a method? available to that method. Declare it in a class (outside any method)? Available to the instance of the class.
calo
Jan 26, 2:46 PMThanks a lot as always
catypus
Oct 25, 6:31 AMCan't do the last challenge because the picture isn't loading
Image placeholder with title "colored-code"
Learneroo
Oct 25, 7:18 PMSorry about that, it's been fixed.