You are on page 1of 5

Java Programming Ing. Matilde Montealegre Madero, MSc.

April 12/19

Access Modifiers : Java offers four choices of Examples that Compile and do not compile
access modifiers: public void walk1() {}
public The method can be called from any class. default void walk2() {} // DOES NOT COMPILE
private The method can only be called from void public walk3() {} // DOES NOT COMPILE
within the same class. Only code in the same void walk4() {}
class can call private methods or access private public void walk1() {}
fields. public final void walk2() {}
protected The method can only be called from public static final void walk3() {}
classes in the same package or subclasses. public final static void walk4() {}
Default (Package Private) Access The method can public modifier void walk5() {} // DOES NOT
only be called from classes in the same COMPILE
package. only classes in the package may access public void final walk6() {} // DOES NOT
it. This one is tricky because there is no keyword COMPILE
for default access. You simply omit the access final public void walk7() {}
modifier. public void walk1() { }
Optional Specifiers : There are a number of public void walk2() { return; }
optional specifiers, but most of them aren’t on the public String walk3() { return ""; }
exam. Optional specifiers come from the public String walk4() { } // DOES NOT
following list. Unlike with access modifiers, you COMPILE
can have multiple public walk5() { } // DOES NOT COMPILE
specifiers in the same method (although not all String walk6(int a) { if (a == 4) return ""; } //
combinations are legal). When this happens, DOES NOT COMPILE
you can specify them in any order. And since it is public void walk1() { }
optional, you can’t have any of them at all. This public void 2walk() { } // DOES NOT COMPILE
means you can have zero or more specifiers in a public walk3 void() { } // DOES NOT COMPILE
method declaration. Only this 3 are covered on the public void Walk_$() { }
exam. public void() { } // DOES NOT COMPILE
static Used for class methods. public void walk1() { }
abstract Used when not providing a method body. public void walk2 { } // DOES NOT COMPILE
final Used when a method is not allowed to be public void walk3(int a) { }
overridden by a subclass.
public void walk4(int a; int b) { } // DOES NOT
COMPILE
public void walk5(int a, int b) { }
public void walk1() { }
public void walk2; // DOES NOT COMPILE
public void walk3(int a) { int name = 5; }
public void walk1(int... nums) { }
public void walk2(int start, int... nums) { }
public void walk3(int... nums, int start) { } //
DOES NOT COMPILE
public void walk4(int... start, int... nums) { } //
DOES NOT COMPILE
Can you figure out why each method call outputs
what it does?
15: public static void walk(int start, int... nums) {
16: System.out.println(nums.length);
17: } Private Access
18: public static void main(String[] args) { This is perfectly legal code because everything is
19: walk(1); // 0 one class:
20: walk(1, 2); // 1 1: package pond.duck;
21: walk(1, 2, 3); // 2 2: public class FatherDuck {
22: walk(1, new int[] {4, 5}); // 2 3: private String noise = "quack";
23: } 4: private void quack() {
You’ve seen that Java will create an empty array if 5: System.out.println(noise); // private access is ok
no parameters are passed for a vararg. However, it 6: }
is still possible to pass null explicitly: 7: private void makeNoise() {
walk(1, null); // throws a NullPointerException 8: quack(); // private access is ok
Since null isn’t an int, Java treats it as an array 9: } }
reference that happens to be null. It just passes on So far, so good. FatherDuck makes a call to
the null array object to walk. Then the walk() private method quack() on line 8 and uses private
method throws an exception because it tries to instance variable noise on line 5.
determine the length of null. Now we add another class:
Accessing a vararg parameter is also just like 1: package pond.duck;
accessing an array. It uses array indexing. 2: public class BadDuckling {
For example: 3: public void makeNoise() {
16: public static void run(int... nums) { 4: FatherDuck duck = new FatherDuck();
17: System.out.println(nums[1]); 5: duck.quack(); // DOES NOT COMPILE
18: } 6: System.out.println(duck.noise); // DOES NOT
19: public static void main(String[] args) { COMPILE
20: run(11, 22); // 22 7: } }
21: }
Default (Package Private) Access
package pond.duck;
public class MotherDuck {
String noise = "quack";
void quack() {
System.out.println(noise); // default access is ok
}
private void makeNoise() {
quack(); // default access is ok
}}
package pond.duck; protected String text = "floating"; // protected
public class GoodDuckling { access
public void makeNoise() { protected void floatInWater() { // protected access
MotherDuck duck = new MotherDuck(); System.out.println(text);
duck.quack(); // default access }}
System.out.println(duck.noise); // default access Next we create a subclass:
}} package pond.goose;
package pond.swan; import pond.shore.Bird; // in a different package
import pond.duck.MotherDuck; // import another public class Gosling extends Bird { // extends
package means create subclass
public class BadCygnet { public void swim() {
public void makeNoise() { floatInWater(); // calling protected member
MotherDuck duck = new MotherDuck(); System.out.println(text); // calling protected
duck.quack(); // DOES NOT COMPILE member
System.out.println(duck.noise); // DOES NOT }}
COMPILE Remember that protected also gives us access to
}} everything that default access does.
This means that a class in the same package as
Protected Access Bird can access its protected members.
Protected access allows everything that default package pond.shore; // same package as Bird
(package private) access allows and more. The public class BirdWatcher {
protected access modifier adds the ability to public void watchBird() {
access members of a parent class. Bird bird = new Bird();
bird.floatInWater(); // calling protected member
System.out.println(bird.text); // calling protected
member
}}
Since Bird and BirdWatcher are in the same
package, BirdWatcher can access members
of the bird variable. The defi nition of protected
allows access to subclasses and classes in
the same package. This example uses the same
package part of that defi nition.
Now let’s try the same thing from a different
package:
package pond.inland;
import pond.shore.Bird; // different package than
Bird
public class BirdWatcherFromAfar {
public void watchBird() {
Bird bird = new Bird();
bird.floatInWater(); // DOES NOT COMPILE
System.out.println(bird.text); // DOES NOT
COMPILE
}}
First, we create a Bird class and give protected BirdWatcherFromAfar is not in the same package
access to its members: as Bird and it doesn’t inherit from
package pond.shore; Bird. This means that it is not allowed to access
public class Bird { protected members of Bird.
Got that? Subclasses and classes in the same
package are the only ones
allowed to access protected members. System.out.println(other.text);
There is one gotcha for protected access. Consider }
this class: public void helpOtherGooseSwim() {
1: package pond.swan; Bird other = new Goose();
2: import pond.shore.Bird; // in different package other.floatInWater(); // DOES NOT COMPILE
than Bird System.out.println(other.text); // DOES NOT
3: public class Swan extends Bird { // but subclass COMPILE
of bird }}
4: public void swim() { The fi rst method is fi ne. In fact, it is equivalent to
5: floatInWater(); // package access to superclass the Swan example. Goose extends Bird. Since we
6: System.out.println(text); // package access to are in the Goose subclass and referring to a Goose
superclass reference, it can access protected members. The
7: } second method is a problem. Although the object
8: public void helpOtherSwanSwim() { happens to be a Goose, it is stored in a Bird
9: Swan other = new Swan(); reference. We are not allowed to refer to members
10: other.floatInWater(); // package access to of the Bird class since we are not in the same
superclass package and Bird is not a subclass of Bird.
11: System.out.println(other.text);// package What about this one?
access to superclass package pond.duck;
12: } import pond.goose.Goose;
13: public void helpOtherBirdSwim() { public class GooseWatcher {
14: Bird other = new Bird(); public void watch() {
15: other.floatInWater(); // DOES NOT Goose goose = new Goose();
COMPILE goose.floatInWater(); // DOES NOT COMPILE
16: System.out.println(other.text); // DOES NOT }}
COMPILE This code doesn’t compile because we are not in
17: } the Goose class. The floatInWater() method is
18: } declared in Bird. GooseWatcher is not in the same
one of the most confusing points on the exam. package as Bird, nor does it extend Bird. Goose
Looking at it a different way, the protected rules extends Bird. That only lets Goose refer to
apply under two scenarios: floatInWater() and not callers of Goose.
■ A member is used without referring to a If this is still puzzling, try it out. Type in the code
variable. This is the case on lines 5 and 6. In and try to make it compile. Then reread this
this case, we are taking advantage of inheritance section. Don’t worry—it wasn’t obvious to the
and protected access is allowed. authors the fi rst time either!
■ A member is used through a variable. This is the Public Access
case on lines 10, 11, 15, and 16. Protected access was a tough concept. Luckily, the
In this case, the rules for the reference type of the last type of access modifi er is easy: public means
variable are what matter. If it is a anyone can access the member from anywhere.
subclass, protected access is allowed. This works package pond.duck;
for references to the same class or a public class DuckTeacher {
subclass. public String name = "helpful"; // public access
We’re going to try this again to make sure you public void swim() { // public access
understand what is going on. Can you System.out.println("swim");
fi gure out why these examples don’t compile? }}
package pond.goose; DuckTeacher allows access to any class that wants
import pond.shore.Bird; it. Now we can try it out:
public class Goose extends Bird { package pond.goose;
public void helpGooseSwim() { import pond.duck.DuckTeacher;
Goose other = new Goose(); public class LostDuckling {
other.floatInWater(); public void swim() {
DuckTeacher teacher = new DuckTeacher(); The story has a happy ending. LostDuckling has
teacher.swim(); // allowed learned to swim and can fi nd its parents— all
System.out.println("Thanks" + teacher.name); // because DuckTeacher made them public.
allowed To review access modifi ers, make sure you know
}} why everything in Table 4.2 is true.
LostDuckling is able to refer to swim() and name Remember that a member is a method or field.
on DuckTeacher because they are public.

You might also like