This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
http://www.javaranch.com/maha/_Mock_Exams/JohnJuntMockExam.htm Q. 30 What class must an inner class extend: A. The top level class B. The Object class C. Any class or interface D. It must extend an interface Select the most appropriate answer. Answer C. Isn't it true that a inner class cannot extend it's outer class? So the answer C. Any class or interface would be wrong. Also all objects extend from Oject either explicitly or implicitly so would correct answer be B?
Originally posted by John Towell: Isn't it true that a inner class cannot extend it's outer class?
Where did you hear that? Try compiling this:
I think you'll find that it compiles just fine. It is perfectly legal for an inner class to extend its enclosing class.
Also all objects extend from Oject either explicitly or implicitly so would correct answer be B?
It's true that, somewhere along the way, all classes obtain the attributes of Object, but that's not the normal way that we think about it. In Java, each class can only extend one class. There is no such thing as multiple inheritance in Java. Therefore, If class A extends class B and class B extends Object, we don't say that class A extends Object. True, class A does obtain the traits of the Object class, we just don't look at as if A extended Object directly. Rather, you say that A extends B and obtains all of the traits of class B, which happen to include the traits of Object, which class B inherited. You can put up a pretty good argument about this, but the point of the question is simply to make you realize that an inner class can extend any class - there is no requirement as to what is can and can't extend. I hope that helps, Corey
John, I agree that the wording of the question could be improved. For example, the question could have asked for all correct answers or only the most correct answer. Also, I assume the author was referring to the enclosing class rather then the "top level" class in answer A. Apparently, an inner class can extend the enclosing class.
It would be interesting to see if anyone can suggest a good application for this option.
If you find yourself looking around for additional mock exams, then I hope that you will try mine at the URL contained in my signature.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Joined: Jul 26, 2002
Thnaks for the replies guys. I didn't know that an inner class could extend it's outer class. That's cool. I will definately try out your practice exams Dan. -John