Hi all, Here's I believe a good brain teaser. Ideas and explanations are appreciated.
What is the output of trying to compile and run it: A. Compiles, but throws a NullPointerException at run time. B. Doesn't compile because Base doesn't implement doAction() method properly. C. Doesn't compile because of the call to a static variable mySub from a non-static context. D. Compiles just fine and runs with output of 20. E. Compiles just fine and runs with output of 10.
hi Vad: Here is what I think: Class <Sub> inhereted interface <I> from its parent class <Base>. interface <I> has a member <i>. Class <Sub> redefind member <i> which it inhereted from Class <Base>. In this case, Sub.i obsecure I.i So when you call <b.mySub.i;>. The Class <Sub> version of <i> will be called. answer: compile just fine and print 20. corect me if I am wrong. Hanna
SCJD 1.4<br />SCJP 1.4<br />-----------------------------------<br />"With regard to excellence, it is not enough to know, but we must try to have and use it.<br />" Aristotle
Hanna, you've asked the question that made me like that code in the first place. mySub is null indeed, but it needs not be instantiated to use its static field i: static fields use their class rather than instance! In other words, an object of type Sub doesn't have to exist to invoke its static methods or access static members. I guess you realize that mySub is static and final itself when declared in the I interface.
Hi y'all, Like what Hanna said the code compile fine and print 20 for me Base b = new Sub(); means that you have a reference of type Base and all the method in Base will be executed in the instace of Sub(polymorphism... right?). But all the variables in Base including those constant variable/s in interface I(since all interface variable are implicitly public static and final) is in instance variable "b"(variable "b" has all those attribute inherited by Base) since concrete classBase implements interface I and Sub extends Base which Sub inherits "mySub" a constant variable in interface I its just like Sub declare a variable on its own type.
I made I a class and made the neccessary changes. It still compiles and now executes with an output of 23. The key to this conundrum is that Sub.i is static, and the reference to it (b.mySub.i) 'flies in the face' of the contract to refer to class members as Class.member rather than instance.member, which doesn't detract from it being a good thing to know.