We looked at making fields private a couple of exercises back, but there were a lot of other things going on, too. So this exercise focuses on just that.
There are three instance variables (A.K.A. “fields”) in this object. One is public, one is private, and one has an unspecified access level, which means it defaults to something called “package-private”.
You’ll notice that this object also has two constructors. The first constructor (lines 7-9) has no parameters, so it’s called the “default” constructor or sometimes the “zero-argument” constructor. The second constructor runs from line 11 through 14 and has three String parameters.
That means whenever the driver instantiates a
FieldAccess object, it can
either do it with no arguments like
new FieldAccess(), or it must pass
in three Strings.
You’ll also see the usual getters and setters for the fields.
On line 3 of the driver we instantiate a
FieldAccess object in the expected
way: call the constructor and pass in three strings. Line 4 shows that it
has been constructed correctly.
Lines 6 through 8 change the fields “properly”: by using the setter (mutator) methods.
On lines 11 through 13 we access all three fields “incorrectly”: directly. The field first actually works; it is public, after all. Accessing last directly wouldn’t even compile, which is why it’s commented out.
And printing out the nick field also works. Remember that a field without an access-level modifier defaults to package-private, which means that any code defined in the same package can touch that variable. We haven’t learned about packages yet (and won’t for a while yet), so all the programs you have written so far are all in the same (unnamed) package.
Hopefully that was a pretty simple exercise, and there weren’t any surprises.
“Learn Object-Oriented Java the Hard Way” is ©2015–2016 Graham Mitchell