Time: Sun 9/24/17 2 pm
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!)
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.
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 calledgulgate
with parameter of typeBird
from theBird
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.
Suppose we make a call to bird.gulgate(bird)
;
Which features are sufficient alone for this call to compile?
Solution
F1
Select a maximum set of features such that this call executes the Bird::gulgate(Bird)
method.
Solution
F1 & not F3 & F2, F4
Select a minimum set of features such that this call executes the Falcon::gulgate(Bird)
method.
Solution
F1 & F3
Suppose we make a call to falcon.gulgate(falcon)
;
Which features are sufficient alone for this call to compile?
Solution
F1 & F2 & F3 & F4
Select a maximum set of features such that this call executes the Bird::gulgate(Bird)
method.
Solution
F1
Select a maximum set of features such that this call executes the Bird::gulgate(Falcon)
method.
Solution
F1 & F2 & F3
Select a maximum set of features such that this call executes the Falcon::gulgate(Bird)
method.
Solution
F1 & F3
Select a maximum set of features such that this call executes the Falcon::gulgate(Falcon)
method.
Solution
F1 & F2 & F3 & F4
Figure out function call by the static type of the object, then call the function by the dynamic type.