Java Reference
In-Depth Information
storing data: variaBles
In the previous section, I defined the simple class outline as follows. A class contains a block of vari-
able definitions (data) and methods (behaviors), like so:
class CLASSNAME {
// VARIABLE DEFINITIONS
// METHOD DEFINITIONS
}
You will now zoom in further on the aspect of defining variables within a class. Specifically, this
section discusses:
Instance variables: Variables that will be used to hold data of objects.
Class variables: Variables that are not bound to an object but instead belong to the class as
such, that is, to the blueprint of the object.
Final variables: Variables that—after their initial assignment—cannot be modified.
Finally, I will also devote some words to the topic of variable scope . A scope of a variable is the
context in which it's defined. This means that, depending on how you define a variable, it will affect
where and how this variable can be accessed.
instance variables
In object‐oriented programming, an instance variable is a variable that's defined in a class (as you
have done before for firstName and lastName in the Student class, for instance). Instance vari-
ables are also commonly referred to as member variables or fields of a class.
Instance variables belong to objects, meaning that each object of the class keeps a separate copy of
this variable. Let's illustrate this idea with an example: instance variables can be introduced by sim-
ply defining them in the class body. Let's say you want to create a class for the concept of a book.
The bare‐bones class then looks like this:
class Book {
}
(Feel free to follow along in Eclipse.) An empty class it not much fun to work with, so you need to
think of some data. Well, since topics have a title and an author, you might want to deine some
variables to represent this. Since a book can have multiple authors, you might even want to define
this data aspect as a composite data type. Perhaps something like the following:
class Book {
String title;
String[] authors;
}
 
Search WWH ::




Custom Search