As I prepare to test for my Java certifications, I am frequently reminded that patience is not always a virtue. See below:
03. class Alpha {
04. static String s = " ";
05. protected Alpha() {
06. s += "alpha ";
07. }
08. }
09. class SubAlpha extends Alpha {
10. private SubAlpha() {
11. s += "sub ";
12. }
13. }
14. public class SubSubAlpha extends Alpha {
15. private SubSubAlpha() {
16. s += "subsub ";
17. }
18. public static void main( String[] args ) {
19. new SubSubAlpha();
20. System.out.println( s );
21. }
22. }
What is the result?
A. subsub
B. sub subsub
C. alpha subsub
D. alpha sub subsub
E. Compilation fails
F. An exception is thrown at runtime
Answer: C is correct. Watch out, because SubSubAlpha extends
Alpha! Since the code doesn't attempt to make a SubAlpha, the
private constructor in SubAlpha is okay.
Yes, I must concede that I got this particular question wrong. And you know what? I’m not going to lose a bit of sleep over it. While I regularly use private
constructors in my classes, I have yet to use them in tandem with any descendents of said classes. If I was willing (or perhaps able) to spend more than two or three minutes on the problem during the exam, the private
constructor would have received additional scrutiny and led me along a path to the correct answer.
The point is this: I could have made the investment of an hour and I never would have noticed the SubSubAlpha extends Alpha
bullshit, which serves as a nearly instantaneous escape hatch for the inexperienced and superficially intelligent. People who write obnubilated code and excel at these types of questions are the kind you want working for your competitors, not with you.
Subsubalphasubalphasubsub extending alpha subsubalphadelta
I didn’t know you were preparing for certification.