CS 61B

Time: Sun 9/24/17 2 pm

Access Control

Discuss public, protected and private members in a Java class. Which one has the highest order?

There's something called package-private, which goes side by side with Java packages (a little bit); where does it sit in the hierarchy of accessibilities? Though there's not an explicit package-private access modifier, the class members are default to have such accessibility.

What can be a good practical practice in coding? Leaving everything package-private? Making everything private?

Read more about Controlling Access to Members of a Class on the documentation for Java 8. (Btw, Java 9 is out!)

Type Casting

Potpourri (sp17-mt1-3)

  1. Suppose Cat and Dog are subclasses of Animal. All three classes have default (zero-argument) constructors. For each answer below, mark whether it causes a compilation error, runtime error, or runs successfully. Consider each line independently of all other lines.

    Cat c = new Animal();

    Solution Compilation error

    Animal a = new Cat();

    Solution Runs fine

    Dog d = new Cat();

    Solution Compilation error

    Animal a = (Cat) new Cat();

    Solution Runs fine

    Dog d = (Dog) new Animal();

    Solution Runtime error


Upcasting should work without getting any compilation errors. Downcasting will get compilation error when without the parenthesis to force the type casting; however, forced type casting can potentially be open to runtime exceptions.

Overriding & Overloading

Flirbocon (sp17-mt1-4)

Consider the declarations below. Assume that Falcon extends Bird.

Bird bird = new Falcon();
Falcon falcon = (Falcon) bird;

Consider the following possible features for the Bird and Falcon classes. Assume that all methods are instance methods (not static!).

The notation Bird::gulgate(Bird) specifies a method called gulgate with parameter of type Bird from the Bird class.

F1. The Bird::gulgate(Bird) method exists.
F2. The Bird::gulgate(Falcon) method exists.
F3. The Falcon::gulgate(Bird) method exists.
F4. The Falcon::gulgate(Falcon) method exists.

  1. Suppose we make a call to bird.gulgate(bird);

  2. Suppose we make a call to falcon.gulgate(falcon);


Figure out function call by the static type of the object, then call the function by the dynamic type.