• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

inner class. can anyone explain me this question.

 
Pankaja Shinde
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is the output of the following code when compiled and run? Select two correct answers.

public class Question25 {
static class Question25Inner {private int i=2;}
static Question25Inner inner = new Question25Inner();
public static void main(String[] args){
Question25[] q25 = new Question25[2];
for(int i=0;i<q25.length;i++)
q25[i] = new Question25();
q25[0].inner.i = 3;
System.out.println(q25[0].inner.i+","+q25[1].inner.i);
}
}


A. Prints: 3,2
B. Compilation error (i is not accessible).
C. Prints: 3,3
D. There are q25.length instances of class Question25Inner.
E. Question25Inner is called a "top-level nested class".

Explain me in detail.

pankaj shinde
[ October 29, 2007: Message edited by: Pankaja Shinde ]
 
Ashok Kumar
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Let us know your analysis on the question and then ask your doubts....
[ October 29, 2007: Message edited by: Ashok Kumar ]
 
Amarbir Singh
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Pankaj,

You are refering to the static inner class... and anything which is in the static context has Class level scope.

so, when you are changing the value of "i" which is a memeber of the static class and hence is in the static context, therefore in fact you are altering a static member value and the same"ll be reflected to all the instances.

I hope it clarifies your doubt.

"The Art Of People Is The True Mirror Of Their Minds...!"
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15480
43
Android IntelliJ IDE Java Scala Spring
 
veda vyas sista
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1.public class Question25 {
2.static class Question25Inner {private int i=2;}
3.static Question25Inner inner = new Question25Inner();
4.public static void main(String[] args){
5.Question25[] q25 = new Question25[2];
6.for(int i=0;i<q25.length;i++)
7.q25[i] = new Question25();
8.q25[0].inner.i = 3;
9.System.out.println(inner.i);
System.out.println(q25[0].inner.i+","+q25[1].inner.i);
}
}



Since inner class is static and i is the variable of i once you change the value of i it will effect the whole i value. After step 8 the i value is totally changed to i if you want you can insert code as
System.out.println(i); to know the i value which is 3.First answer is 3,3.

Also second answer is static inner class is top-level nested class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic