Question 26 abstract class A { private int x = 4; private int y = 2; public int x() {return x;} public void x(int x) {this.x = x;} public int y() {return y;} public void y(int y) {this.y = y;} } interface B {int math();} class C { static class D extends A implements B { public int math() {return x()+y();} } static A a1 = new A() implements B { public int math() {return x()+y();} }; public static void main(String[] args) { System.out.print(new C.D().math()); System.out.print(a1.math()); }} What is the result of attempting to compile and run the program? a. Prints: 12 b. Prints: 66 c. Compile-time error d. Run-time error e. None of the above Answer = c because an anonymous class referenced by a1 : static A a1 = new A() implements B {cannot haven an implements clause ! I also thought a compile error but for even a different reason i.e. you cannot instantiate (Static A a1 =....)an abstract class (must be extended). Is this true or am I wrong ? Kristof
Dan Chisholm
Ranch Hand
Joined: Jul 02, 2002
Posts: 1865
posted
0
Kristof, The code does not attempt to instantiate an abstract class. Instead, the code attempts to create an instance of anonymous class that extends an abstract class. Since the anonymous class has no abstract methods, there would be no compile-time error due to the abstract modifier appearing in the superclass declaration. Having said the above, I don't like my code example in that question, because it is too complex. I think I'll replace it with the following.
Kristoff, you can preserve the formatting of code block by using the UBB tage named "CODE". Just click the CODE button and then paste the program inside the tags.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>