• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Jeanne Boyarsky
  • Tim Cooke
  • Knute Snortum
  • Junilu Lacar
  • Devaka Cooray
Saloon Keepers:
  • Ganesh Patekar
  • Tim Moores
  • Carey Brown
  • Stephan van Hulst
  • salvin francis
  • Ron McLeod
  • Frits Walraven
  • Pete Letkeman

question on inner class  RSS feed

Ranch Hand
Posts: 1277
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Question : taken from Voodoo exam Exam_3
Given the following class file , how can you get a reference to an object of type Inner ?

class Outer {
// some valid lines of code
static class Inner {
//some more valid lines of code

Options :
a . new Outer ( ) . new Inner ( )
b . Outer . new Inner ( )
c . new Outer . Inner ( )
d . Outer . Inner ( )

the question doesnt specify where in the code are we supposed to put the above options
as per the test software the answers are - a,c

please explain
thanks in advance
Posts: 17314
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it assuming you see that it says class file and you want to create an instance of the Inner class, and a and c are the correct answers.

Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, there are a couple of problems here.

First, the question asks about a an object of type "Inner," but the type is actually Outer.Inner. Because the nested class is static, it can be instantiated without an instance of the outer class, so (if we assume type Outer.Inner) C is correct...

Outer.Inner i = new Outer.Inner();

The second problem is more serious. As defined in section 8.1.3 of the JLS, "An inner class is a nested class that is not explicitly or implicitly declared static." So in this example, "Inner" is not really an inner class. More than just being misleading, this turns out to be key to the answer.

You might expect that it would be possible to instantiate Outer.Inner using an instance of Outer, as in option A. In fact, this was possible prior to Java 1.4, but it now gives a compilation error of "qualified new of static class." This was reported as a bug, but Sun closed it as "not a bug," citing section 15.9.1 of the JLS: "It is a compile-time error if Identifier [in this case, "Inner"] is not the simple name (�6.2) of an accessible (�6.6) non-abstract inner class (�8.1.2)..."

In other words, because Inner is static, it is not an inner class, and therefore cannot be instantiated using an instance of the enclosing class.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!