• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Marcus green exam 2 : question 32

 
Milind Deodhar
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This question about Inner class
******************************************************************
public class Outer{
public String name = "Outer";
public static void main(String argv[]){
Inner i = new Inner();
i.showName();
}//End of main
private class Inner{
String name =new String("Inner");
void showName(){
System.out.println(name);
}
}//End of Inner class
}
4) Compile time error because of the line creating the instance of Inner

This looks like a question about inner classes but it is also a reference to the fact that the main method is static and thus you cannot directly access a non static method. The line causing the error could be fixed by changing it to say
Inner i = new Outer().new Inner();
Then the code would compile and run producing the output "Inner"
*****************************************************************
I think that the compiler gives an error message for having private as a modifier.
Secondly, when I move the Inner = new Inner(); after the class declaration the class compiles fine. So the explanation given that static cannot access non static is wrong, becasue the class itself is defined in static method.
I think answer and explanation is wrong.
can someone clarify
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have an inner class be private, that just means you cannot access the inner class outside of class Outer.
The reason it won't compile the first time is because you are trying to create an instance of Inner i without a reference to an Outer. If you changed that line to be Outer.Inner i = new Outer().new Inner(); then it would compile. As for your assumption, if you move Inner i = new Inner() right after the class declaration, that still won't work because the static method main is trying to access the non-static variable i.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic