Java Reference
In-Depth Information
continued
Book myNewbook = giveMeABook();
// Forgot the check for null?
System.out.println("Title equals: "+myNewBook.title);
// This will give an error
NullPointerException errors are a prevalent problem when programming in
Java, and oftentimes it is hard to track down the root cause behind them as you
have to track down where and why a particular object has not been instantiated
(i.e., the variable equals null ). Therefore, it is a good idea either to program
defensively and always check for null when retrieving an object and before
moving on with using the object, or to program in such a way that only in a lim-
ited number of cases a null variable is passed from one part of your program to
another.
This code also immediately illustrates that you are not forced to use the default values for instance
variables. For example, you can modify the Book class to assign defaults to the title and author
variables:
class Book {
String title = "Unknown Title";
String[] authors = new String[]{"Anonymous"};
}
And, combining this with the knowledge on how to define multiple variables of the same type in one
go, you can add:
class Book {
String title = "Unknown Title";
String[] authors = new String[]{"Anonymous"};
int yearReleased = 2014, copiesSold = 0;
}
With this knowledge under your belt, you might be wondering, as each object keeps its own copy of
instance variables, is there also a way to define a common variable, something that's shared between
all objects belonging to the same class? Indeed there is . . .
class variables
In object‐oriented programming, a class variable , also denoted as a static variable, is a vari-
able that's been allocated “statically”—meaning that this variable is shared between all objects
(instances) belonging to this class. Further, since class variables belong to the class blueprint, it is not
necessary to create objects to be able to access and modify class variables. It is sometimes argued
that class variables do not really adhere to “pure” object‐oriented programming principles. Other,
stricter programming languages, such as Scala, do not allow them, for instance. That said, this is
not to be regarded as a shortcoming of Java, as we will see that class variables can come in handy in
many cases. However, it is best not to overuse them.
 
Search WWH ::




Custom Search