How can we create Instance to Inner Class ?

Discussion in 'Inner Classes' started by vbraojava, Sep 10, 2008.

  1. vbraojava

    vbraojava New Member

    Objects that are instances of an Inner Class exist within an instance of the Outer Class only. An object to Inner Class can't be created in other Classes.

    As with instance methods and variables, an Inner Class is associated with an instance of its Outer Class, it has direct access to that Outer Class object's methods, variables and fields.

    To instantiate an Inner Class, you must first instantiate the Outer Class. Then, create the Inner Object within the Outer Object.

    Example : OuterClass.InnerClass innerObject = outerObject.new InnerClass();
     
  2. see the example below

    package org.sonalit.testing;

    public class InnerClassTest {

    private int x;
    public class Inner{

    private int y;
    private int x = 5;
    public void innerMethod(){
    System.out.println("y is " + y);
    System.out.println("x is " + this.x);
    System.out.println("x is " + InnerClassTest.this.x);
    }
    }
    private class Inn{
    public void privateM(){
    System.out.println("hai");
    }
    }
    public void outerMethod(){
    // System.out.println("y is " + y);
    }
    public static void main(String arg[]){
    InnerClassTest ic = new InnerClassTest();

    InnerClassTest.Inner in = ic.new Inner(); //public inner class
    in.innerMethod();
    InnerClassTest.Inn ip = ic.new Inn(); // private inner class
    ip.privateM();

    }
    }
     
  3. anneroberts

    anneroberts Member

    With instantiate a inward class, you must principal instantiate the external population. Then, make those internal article inside the external article for this syntax: OuterClass. InnerClass innerObject = outerObject. New InnerClass();.
     

Share This Page