• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Inner Class Instantiation

 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All!
Here is question 3 from Valiveru's exam:
Given the code below
1public class OuterClass{
2 public class InnerClass{
3public InnerClass(){
4 System.out.println("I am in InnerClass");
5}
6 }
7 public static void main(String[] arg){
8//
9 }
10}
Which of the following valid code replacement at line 8
A.OuterClass.InnerClass i = new InnerClass();
B.InnerClass i = new InnerClass();
C.OuterClass.InnerClass i = new
OuterClass().new InnerClass();
D.OuterClass o = new OuterClass();
InnerClass i = o.new InnerClass();
E.OuterClass.InnerClass i = this.new InnerClass();
The correct answers are said to be c and d.
As far as I know the only way to make an inner class object at line 8 is as follows,
InnerClass I = new InnerClass();
Are the answers given correct and am I wrong ?
Thanks in advance,
Prasanna
 
Ranch Hand
Posts: 3141
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Prasanna,
The answers C and D are the correct ones. The answer you thought was right will not work. For each instance of an inner class you need to have an instance of an outer class.
If you try running the code with the answers given you can see how it works.
Hope that helps.
------------------
Jane
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I think C and D are correct, according to the following rule :
"An instance of an inner class cannotbe created without first creating an instance of its outer class".
So,
A. is incorrect because there is no outer class ;
B. is incorrect for the same reason;
C. is correct because the new InnerClass is attached to the new OuterClass created just before
D. is correct because the new InnerClass object is attached to the object o
E. is incorrect because you cannot use "this" within a staic context (which is here the main() method)
Hope this will help.
 
reply
    Bookmark Topic Watch Topic
  • New Topic