This discussion is archived
3 Replies Latest reply: Apr 3, 2013 1:58 AM by rahulras RSS

Question on Inner/nested class

rahulras Explorer
Currently Being Moderated
Hi All,

I want to clear my understanding on Inner classes. I have following Java code
class MyOuterClass
{
  public void PrintName ()
  {
     System.out.println("This is MyOuterClass");
  }
  
  public MyOuterClass() // Outer class constructor
  {
    System.out.println("From constructor of MyOuterClass");
  }
  
  public class MyInnerClass // Inner class declaration
  {
     public MyInnerClass() // Inner class constructor
     {
        System.out.println("From constructor of MyInnerClass");
     }
     
     public void PrintName()
     {
        System.out.println("This is MyInnerClass");
     }
  }
}

public class test
{
   public static void main(String args[])
   {
     MyOuterClass c1 = new MyOuterClass();
     c1.PrintName();
     
     // case 1) MyOuterClass.MyInnerClass i1 = new MyOuterClass.MyInnerClass();
     // case 2) c1.MyInnerClass.PrintName();
   }
}
See the 2 commented lines near the end of code. They are written in an attempt to see output from the constructor of inner class. Both give error.
How/when can I see the constructor of inner class executed?
How can I call PrintName() method from inner class?
What is exactly wrong with statements in case 1 and case 2 ?

Thanks in advance.
  • 1. Re: Question on Inner/nested class
    973635 Newbie
    Currently Being Moderated
    I think it's:
    c1.MyInnerClass i1 = c1.new MyOuterClass.MyInnerClass();
    It's pretty rare to refer to a non-static nested class anywher but from within a method or constructor of the enclosing class, where an OuterClass.this is present (and often implicit).
  • 2. Re: Question on Inner/nested class
    rp0428 Guru
    Currently Being Moderated
    >
    See the 2 commented lines near the end of code. They are written in an attempt to see output from the constructor of inner class. Both give error.
    How/when can I see the constructor of inner class executed?
    How can I call PrintName() method from inner class?
    What is exactly wrong with statements in case 1 and case 2 ?
    >
    You haven't created an instance of the inner class. So there is no instance to call the methods on.

    Modify your code to create an instance of the inner class. When you do the constructor will print out the message.

    Then you can call the PrintName method on that instance.
  • 3. Re: Question on Inner/nested class
    rahulras Explorer
    Currently Being Moderated
    Yes. This worked
    MyOuterClass.MyInnerClass i1 = c1.new MyInnerClass();

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points