field variables
In a previous section, we talked about variables inside of methods. The variables you set up inside of methods are only available to those methods. They are not available to other methods. They are said to have local scope.However, you can set up variables outside of methods that all the methods in your class can see. These are known as Field variables (or Instance variables). You set them up in exactly the same way as any other variable. Add the following four fields to your new StudentResults class:
To see just how global they are, click back on to your ExamDetails class, the one with the main method. Add the following line of code to create a new object from your StudentResults class:
On the next line, type the name of the variable (aStudent), followed by a dot. As soon as you type the dot NetBeans display a popup list of methods and properties available to your object:
You can set values for properties. Try this: add the following highlighted code to your main method:
So the four variables we've set up are now available to both classes.
However, it's not a good idea to make field variables global like this. You tend to lose track of just what values are being held in them, and it therefore makes debugging your code a lot harder. It's considered good coding to narrow the scope of field variables.
To make a field variable available only to a particular class, you add the Java keyword private just before the field declaration. Change the code in your StudentResults class to this:
In the next part, you'll learn about something called a class constructor
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment