Reference to enclosing instance in inner class constructor

Is there any Java compiler which assigns reference to enclosing instance in constructor of inner clase before invoking super class constructor?
class Outer {
class Inner extends Global {
public Inner(int x) {
// I want (Outer.this != null) here
super();
class Global {
public Global(int x) {

class Outer {
class Inner extends Global {
public Inner(int x) {
// I want (Outer.this != null) hereOuter.this is never null at this point. A non-static
inner class always has an implicit reference to an
instance of the enclosing class.Try this:
class Outer {
int m;
class Inner extends Global {
public Inner(int x) {
super(x);
protected void init(int x) {
xxx = Outer.this.m + x; // Null pointer exception!!!
class Global {
int xxx;
public Global(int x) {
init(x);
protected void init(int x) {
xxx = x;

Similar Messages

  • Enclosing instance references....

    Ok, I turned to the holy scripture (JLS), and have turned away baffled.....
    Im confused on an Inner class issue.
    If inner classes are to reference fields of their inclosing instance, they have to be able to reference it some way.
    Im assuming that this is implemented as a field of the inner class (is that a correct assumption?) synthesised at compile time.
    Now, what I want to know is when does this reference (if it exists) become 'valid' when the inner class is a derived class?
    Intuition tells me that it would be null until after the base class constructor had completed. However, in practise this is not always the case....
    Heres an example:
    We have some class:
    class Something {
      public Something() {
        // NOTE: Call non-final method from constructor!!!
        createSomething();
      public Object createSomething() {
        return new Whatever();
    }We then have a class which creates an annonymous inner class which overides the 'createSomething' method:
    class UserClass {
      public void example() {
        final Object toReturn = new Object();
        Something mySomething = new Something() {
          public Object createSomething() {
            // THE ALL IMPORTANT LINE:
            System.out.println("Ref: " + UserClass.this);
            return toReturn;
    }Now, when the mySomething is constructed, the 'createSomething' method is called from the base constructor. At this point, I would expect (incorrectly?) that the enclosing reference (UserClass.this) would be null.
    However, on two compilers, I get two different results. Null on one, non-null on the other.
    Can anyone please explain to me the way this should work - or is it undefined?

    What Im confused about is this:
    The instance of the annonymous inner class has to be able to reference its enclosing instance somehow (I.e, UserClass.this).
    So, Im guessing (perhaps incorrectly...) that the instance of the annonymous inner class will have a field that is a reference to the enclosing class.
    Im fully aware that the enclosing class can never really be null... However, constructors are called bottom up, and a non-final method is called from the base class constructor.
    This is then overidden in the inner class to print out the reference to the enclosing class (UserClass.this).
    My confusion is about when it becomes 'valid' for the inner class to reference its enclosing class (using UserClass.this) - and my intuition says not before the base constructors have been called (I.e, I would expect it to be null in my example).
    Why do I think that?
    Well, if we have this:
    class MyBaseClass {
      public MyBaseClass() {
        dodgyMethod();   
      public void dodgyMethod() {
        System.out.println("HELLO");
    class MyDerivedClass extends MyBaseClass {
      Integer someInteger = new Integer(4);
      public void dodgyMethod() {
        // Will be NULL when called from base constructor
        System.out.println("val: " + someInteger);
    }We see that if a new 'MyDerivedClass' is created, then someInteger is null (because someInteger hasn't been initialised yet, coz we are still in the base class constructor).
    My question is just an extension of the above.....
    If the enclosing instance reference is implemented as a normal ref in the anonymous inner class, I would not expect it to get initialised until the base class constructor had completed (in the same way that I wouldn't expect someInteger to be initialise until its base constructor had completed).
    So its all about calling non-final methods from a base class, where the derrived class is an inner class, and whether or not the enclosing reference should be non-null at that point in time.

  • More:Could u pls complete the following code by adding a class constructor?

    Thank you for your concern about my post. Actually it is an exercise in book "Thinking in Java, 2nd edition, Revision 12" chapter 8. The exercise is described as below:
    Create a class with an inner class that has a nondefault constructor. Create a second class with an inner class that inherits from the first inner class.
    And I make some changes for the above exercise requiring the class which encloses the first inner class has a nondefault constructor.
    There is something related to this topic in chapter 8 picked out for reference as below:
    Inheriting from inner classes
    Because the inner class constructor must attach to a reference of the enclosing class object, things are slightly complicated when you inherit from an inner class. The problem is that the �secret?reference to the enclosing class object must be initialized, and yet in the derived class there�s no longer a default object to attach to. The answer is to use a syntax provided to make the association explicit:
    //: c08:InheritInner.java
    // Inheriting an inner class.
    class WithInner {
    class Inner {}
    public class InheritInner
    extends WithInner.Inner {
    //! InheritInner() {} // Won't compile
    InheritInner(WithInner wi) {
    wi.super();
    public static void main(String[] args) {
    WithInner wi = new WithInner();
    InheritInner ii = new InheritInner(wi);
    } ///:~
    You can see that InheritInner is extending only the inner class, not the outer one. But when it comes time to create a constructor, the default one is no good and you can�t just pass a reference to an enclosing object. In addition, you must use the syntax
    enclosingClassReference.super();
    inside the constructor. This provides the necessary reference and the program will then compile.
    My previous post is shown below, could you help me out?
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    //Could you please help me complete the following code by generating
    // the Test class constructor to ensure error free compilation? Please
    // keep the constructor simple just to fulfill its basic functionality
    // and leave the uncommented part untouched.
    class Outer {
    Outer (int i) {
    System.out.println("Outer is " + i);
    class Inner {
    int i;
    Inner (int i) {
    this.i = i;
    void prt () {
    System.out.println("Inner is " + i);
    public class Test extends Outer.Inner {
    // Test Constructor
    // is implemented
    // here.
    ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    Test(Outer o, int i) {
      o.super(i);
    }Note that this doesn't quite answer the question from Thinking In Java, since your Test class is not an inner class (though there is no difference to the constructor requirements if you do make it an inner class).

  • Inner Classes doubts

    Hi All,
    I am trying to learn Inner classes in Java. I am referring to the book Core Java by Horstmann and Cornell.
    I know that there are various types of inner classes namely:
    - Nested Inner classes
    - Local Inner classes
    - Annonymous Inner classes
    - static inner classes
    First I am on with Nested Inner classes :
    Following is the code which I am executing :
    package com.example.innerclass;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    public class InnerClassTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TalkingClock clock = new TalkingClock(1000,true);
              clock.start();
    //          JOptionPane.showMessageDialog(null,"Quit Program");
    //          System.exit(0);
    class TalkingClock
         private int interval;
         private boolean beep;
         public TalkingClock(int interval, boolean beep){
              this.interval = interval;
              this.beep = beep;          
         public void start(){
              ActionListener listener = new TimePrinter();
              Timer t = new Timer(interval,listener);
              t.start();
         private class TimePrinter implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   Date now = new Date();
                   System.out.println("At the tone time is : "+now);
                   if(beep)
                        Toolkit.getDefaultToolkit().beep();
    }Following are my doubts :
    1. Why do we need to give the line
    JOptionPane.showMessageDialog(null,"Quit Program");
    System.exit(0);without this line the program doesn't show any output.
    2. I didn't understand this syntax.
    You can write inner object constructor more explicitly using the syntax. :
    outerObject.new InnerClass(construction parameters)
    For e.g.
    ActionListener listener = this.new TimePrinter();
    Here the outer class reference of the newly constructed TimePrinter object is set to this reference of the method that creates the inner class object. the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicilty naming it. For e.g if TimePrinter were a public inner class, you could construct a TimePrinter for any talking clock.
    TalkingClock jabberer = new TalkingClock(1000,true);
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    Please do help me understand this concept.
    Thanks
    Siddharth

    I have understood that this explanation :
    i) assuming that TimePrinter is an inner class of TalkingClock, that you'd need an instance of the later in order to create an instance of the former.Yes.
    Being a non-static inner class, it can not be instantiated out of context ... which context is the outer class.No. See my reply 11. The "context" is an instance of the outer class - it bears repeating.
    ii) jabberer is the outer instance that you are providing.Yes (more accurately it's a reference to an instance of the outer class, but that would be nit-picking).
    The left side is identifying the class, the right side is identifying the instanceNo.
    I'm not sure what you're calling left side and right side.
    If you're talking about both sides of the equals sign, then no, it's completely wrong.
    If you're talking about both sides of the "point" sign, then it's wrong too, just a bit less wrong.
    Let's revise this step by step (good thought process).
    1. in first line we are getting an outer class reference with this code
    TalkingClock jabberer = new TalkingClock(1000,true);
    this line is very natural and easily understood. Yes. The correct wording would be merely "we are getting a reference to an instance of the outer class". Sorry to insist densely.
    2. Now when we come to the second line, i.e. where we try to instantiate an inner class with this line of code
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    - I do understand the concept that we need an instance of outer class in order to create an instance of inner class as inner class is visible only to outer class.No. We need an instance of the outer class as the inner class is non-static, and by definition needs an instance of the outer class. That has nothing to do with visibility (public vs private vs...). Again, some words have special meanings in the Java world.
    - I also do understand that it cant be instantiated out of context. I see you like this expression, but it is too vague and misleads you. Please forget about it for a moment (no offense to otherwise helpful and knowledgeable abillconsl).
    - I also do understand that left side is identifying the class and right side is identifying the instance. ANDAgain I'm afraid of which "sides" you're talking about.
    - that in this line TalkingClock.TimePrinter listener = new TalkingClock().new TimePrinter();
    the outer class is anonymous (new TalkingClock()) as we don't require its name here Poor choice of words again. Anonymous classes do exist in Java, but are a totally different concept, that is not related to this line.
    - Also in this line TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    I understood the left side part i.e. TalkingClock.TimePrinter listener =
    We are attaching the outer class reference with the inner class that's absolutely understandable. Not at all!
    This just declares a variable listener, whose type is TalkingClock.TimePrinter (or more accurately com.example.innerclass.TalkingClock.TimePrinter).
    Then follows an assignment:
    WHAT I don't understand is the right hand side, i.e., the statement jabberer.new TimePrinter();
    1. I am unable to digest the fact that we can do something like anobject.new
    new is an operator that is used to instantiate an instance of an object. I am unable to digest that we can do x.new?See my previous reply. This is short-hand syntax Sun chose to pass a reference to an instance of the outer class (here, jabberer) to the constructor of the inner class. They could have chosen something else. Again, bear with it.
    I only know that we can do is new SomeClass(); AND NOT instance.new SomeClass();
    Now you know better:
    The second form is valid - only if SomeClass is a non-static inner class defined in a class of which instance is an instance.
    2. Is there something to this conceptually OR this is only a syntax and that I should learn it.
    I want to understand and grasp if there is some concept behind it rather than just learn and mug up. See my previous reply. Each instance of a non-static inner class stores a reference to an instance of the outer class. There must be a way (a syntax) to specify which instance (of the outer class) should be stored in the instance (of the inner class).
    This particular syntax is just a syntax, the "concept" is that the instance of the inner class stores a (unmodifiable) reference to the instance of the outer class that was specified when the instance of the inner class was created.
    I don't know if that deserves to be called a concept, but that's an interesting thing to keep in mind (there are some not-so-obvious implications in terms of, e.g. garbage collection).
    Best regards.
    J.

  • Doubt in inner classes

    public class Outer
               public static void main(String argv[])
                         Outer o=new Outer(); //1                    
                         Inner i =o.new Inner(); //2
                         //Inner i =new Inner();  //3
         i.showName();   
             public      class Inner{   
                    void showName()
            System.out.println("hi");            
          }//End of Inner class
    }I have few doubt regrd the above program..
    1)when i create an inner class instance as in line 3,..Iam having an err like
    non-static variable this cannot be referenced from a static context.. Bcas Inner is a non static member of class Outer it cant be referred without an instance of Outer as in line 2.. But my doubt is why it doesnt give such error (of static context issue) in the case of line 1...its a silly dbt but iam confused ...
    2..Can we refer the inner class without outer class like in line 2., I have used
    Inner without Outer ..is this ok... or shuld we use as
    Outer.Inner i =o.new Inner(); //2
    3)In the above line We r associating the instance of inner class with the instance of outer class and the type of inner class with the type of outer class (Outer.Inner )..wht does this mean..
    can anyone pls help me understand this..
    thnx.
    mysha..

    public class Outer
    public static void main(String argv[])
    Outer o=new Outer(); //1
    er o=new Outer(); //1                    
    Inner i =o.new Inner(); //2
    //Inner i =new Inner();  //3
         i.showName();   
    public      class Inner{   
    void showName()
            System.out.println("hi");            
    }//End of Inner class
    }I have few doubt regrd the above program..
    1)when i create an inner class instance as in line
    3,..Iam having an err like
    non-static variable this cannot be referenced from a
    static context.. Bcas Inner is a non static member of
    class Outer it cant be referred without an instance
    of Outer as in line 2.. But my doubt is why it doesnt
    give such error (of static context issue) in the case
    of line 1...its a silly dbt but iam confused ...
    Static methods of a class exist as soon as Java loads the class. Regular, or non-static, methods of a class belong to an object and only come into existence after you create an object of the class. Regular methods are called by an object. Static members are called using the class name.
    Now, examine this simple program:
    class Apple
         private String color;
         public Apple(String color)
              this.color = color;
         public void show()
              System.out.println("apple color: " + color);
         public static void greeting()
              System.out.println("Hello from the Apple class.");
    public class  Demo
         public static void main(String[] args)
              Apple.greeting();  //1
              Apple a = new Apple("red");  //2
    }After the Apple class loads, any static methods in the class exist. Since greeting() is a static method of the Apple class, it can be called in line 1 before any Apple objects exist. But, what about line 2? How can the Apple constructor with the String parameter, which is a method in the Apple class, be called? The constructor isn't declared as a static, so it shouldn't exist in that regard, and no objects of the class exist. So, when and how did the constructor come into existence. That seems to be the question you're struggling with. I think the answer is: a constructor sort of acts like a static method. In order to be able to call a constructor, the constructor must exist as soon as the class loads and before any objects exist. The result is, you can call a constructor at any time.
    I think your example is similar to my example, but you only have one class:
    public class Outer
    public static void main(String argv[])
    Outer o=new Outer(); //1
    }After Java loads Outer, any static methods in Outer exist. Since main() is a static method, it exists. Subsequently, java calls the static main() method to begin execution of your program. In line 1, you call the default constructor for Outer. The default constructor isn't static, so it shouldn't exist, but just like the constructor in my example above, the default constructor acts like a static method, and therefore you can call it without getting an error.
    Inner i =o.new Inner(); //2
    2..Can we refer the inner class without outer class
    like in line 2., I have used
    Inner without Outer ..is this ok... or shuld we use
    as
    Outer.Inner i =o.new Inner(); //2
    I'm not sure what the difference is. In both cases you end up with an object that was created with the expression:
    o.new Inner()
    you just have a different type for your object, i.e. Outer.Inner versus Inner.
    3)In the above line We r associating the instance of
    inner class with the instance of outer class and the
    type of inner class with the type of outer class
    (Outer.Inner )..wht does this mean..
    can anyone pls help me understand this..
    I think you said it: it means you have an Inner object that is "associated" with an Outer object. Like any other regular member in the Outer class, Inner can refer to any members of Outer. (A static member of Outer can't refer to regular members of Outer because static members exist before any objects exist, and when no objects exist, the regular members don't exist.) That means an Outer object must exist before you can create an Inner object.

  • Why we are making a variable as final in method inner class ?

    Why we are making the variable as final (method inner class) while we are accessing the method variable in inner class ?
    regards,
    namanc

    As far as I can tell, the only reason is to protect the programmer: when the inner class instance is constructed, it is given the then-current value of the variable. If the variable (or method parameter) later changes, the value held by the inner class would not. By making the variable final, the programmer doesn't have to worry about them staying in sync.
    Here's some code to ponder:
    public class InnerExample
        void printMe( final int x )
            Runnable runMe = new Runnable()
                public void run()
                    System.out.println(x);
            (new Thread(runMe)).start();
    }When compiled with the Sun JDK 1.4.2, you get this bytecode:
    void printMe(int);
      Code:
       0:   new     #2; //class InnerExample$1
       3:   dup
       4:   aload_0
       5:   iload_1
       6:   invokespecial   #3; //Method InnerExample$1."<init>":(LInnerExample;I)V
       9:   astore_2
       10:  new     #4; //class Thread
       13:  dup
       14:  aload_2
       15:  invokespecial   #5; //Method java/lang/Thread."<init>":(Ljava/lang/Runnable;)V
       18:  invokevirtual   #6; //Method java/lang/Thread.start:()V
       21:  returnAt line (byte) 5, it loads the passed value onto the stack; at line 6, it invokes the inner class constructor (which is created by the compiler). Nothing in this sequence of code would prevent use of a non-final variable.

  • Inner class access to its creator

    Hi there,
    From a subclass of Action I have created as a (non-static) inner class of a JFrame, I wish to reference the parent JFrame in a JFileChooser invocation, so something like:JFileChooser.showSaveDialog(**this**);with **this** being the parent JFrame.
    One option I can think of is to pass through "this" when I instantiate the action, but I wondered if there was a language construction that provided this information directly.
    I tried a search through the forums using "parent of an inner class" but found nothing useful. Is there a mechanism to provide this, or is passing "this" through to the inner class the only option?
    Thanks for any help you can provide.
    Tim

    To access wrapper instance of inner class, you can use WRAPPER_INSTANCE_CLASS.this keyword.
    For example:
    public class a {
       int value = 0;
       public void doSomething() {
          Object dummy = new Object() {
              public String toString() {
                  a.this.setSomething(10);
                  return a.this.toString();
          System.out.println(dummy);
       public void setSomething(int x) {
          value = x;
       public String toString() {
          return "class a, the value now is " + value;
       public static void main (String s[]) {
           new a().doSomething();
    }note that I use a.this.setSomething(10);
    a is the wrapper class, so a.this refers to the wrapper instance, not current instance.
    rgds,
    Alex

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

  • EJB fails to compile - static inner class problem

    I am using OC4J 9.0.4 and Sun JDK1.4.2 and EJBs fail to compile if they reference objects that contain static inner classes. However, they successfully compile under JDK1.4.1.
    For example, I have a class like below:
    public class ValueObject
    public static class Key
    private Key key;
    private String value;
    Any references to ValueObject.Key inside the EJB cause the EJB compiler to generate "ValueObject$Key" which is incorrect. JDK1.4.1 is more lenient than 1.4.2, and allows this error through.
    Is there a way around this problem other than reverting to JDK1.4.1?
    Regards,
    Andy

    The reason I don't want to move to JDK 1.4.1 is because of the memory leak in the StringBuffer.toString() method.
    Is there anywhere I can submit this as a bug?
    Regards,
    Andy

  • Enclosing Instances When Subclassing Inner Classes

    Hi,
    I need to subclass an inner class but when I write code for its constructor I get the error "an enclosing instance that contains at.MainHandler.innerClass is required".
    at.MainHandler is my outer class and my new class looks something like this:
    public class newClass extends at.MainHandler.innerClass {
         //Constructor
         public newClass (int a, int b) {
             super( a );
        }//Constructor
    }//ClassI understand that the inner class to which 'super' refers must somehow be bound to its outer class(at.MainHandler) if I want newClass to access the outer class methods, but what is the correct syntax needed to achieve this?
    I've looked at other posts on similar topics but am still unable to grasp precisely what is needed.
    Sid

    These are some working examples:
    class A {
         class InA {}
    class B extends A {
         class InB extends InA {}
    class A {
         static class InA {}
    class InB extends A.InA {}
    class A {
         class InA {}
    class InB extends A.InA {
         InB(A a) {
              a.super();
    }

  • Can enclosing instance for an inner class be null?

    I have a class Solution, which defines an inner class, SolutionStep.
    In a third class I construct several SolutionStep objects, and later use them to construct a Solution.
    In this third class I have statements like this:
    Solution solution = null;
    aCollection.add(solution.new SolutionStep(arg1, arg2);
    This has been working fine, but recently a customer reported an error,which seems to be a NullPointerException at the line above.
    Now that I look at this code, I'm not very happy about it and I'll clean it up, but I am left with the basic question of whether what I'm doing is legal. Can the enclosing instance used to construct an inner class be null? I have not been able to find a definitive answer.
    Any help appreciated.

    Yes, you're right, I dropped a parenthesis. Sorry.
    The offending statement is actually
    aCollection.add(solution.new SolutionStep(arg1,
    arg2));
    And that is certainly legal. The inner class does not
    need to be qualified when it's constructed in the
    context of an enclosing instance.Very interesting.
    The following code demonstrates this....
        class Solution
            class SolutionStep
                public SolutionStep()
        public class ThirdClass
            static public void main(String[] args)
            Solution solution = null;
            //Solution solution = new Solution();  // This produces no null exception.
            Solution.SolutionStep s = solution.new SolutionStep();
    Using jikes and javac doesn't change the behavior so that means it is VM rather than compiler specific.
    I am using 1.4.2_04 on windows and I get the null pointer exception.
    Looking at the javap output suggests that invokespecial has to be checking this (although I could have overlooked something when I checked.)
    This probably comes from the following in the VM spec under invokespecial...
    Otherwise, if objectref is null, the invokespecial instruction throws a NullPointerException.

  • Inner classes can't access parent classes in constructor

    I'm having a problem where I have class A, which has an Inner class B, which has it's own inner class C. In C's constructor (the inner most class), i'm trying to access a method of A (the top most class), and I get a NullPointerException with trace:
    at mearns.finance.DefaultPortfolio.access$0(DefaultPortfolio.java:1)
    at mearns.finance.DefaultPortfolio$AccountsEditor$AccountsTableModel.<init>(DefaultPortfolio.java:253)
    In this case "DefaultPortfolio" is class A, AccountsEditor is class B, and AccountsTableModel is class C. The line given in the second stack trace element is the line in C's constructor which calls Class A's method.
    Debugging, I stop inside C's constructor. Before anything happens, debugger says this$1 is null. Then I step, and it calls super(), and now this$1 is an instance of class B (AccountEditor), but it's own this$1 (which should be an instance of class A) is still null.
    I'm calling C's constructor from within B's constructor (but not A's), not sure if that makes a difference.
    Can anyone explain what's going on here, and (hopefully) how I can work around it?
    Thanks for any help.
    When i debug

    hm, I really don't know what is happening but I want to tell you about something that is not nice in your code and possibly it could cause the error.
    Code behaves somwhat strange when you pass this out of a constructor. You do this implicitly when you create an inner classe which implicitly gets a reference to the outer class. Also just simple method calls can cause such effects.
    This is because the construction process it not finished but methods are already called.
    Even worse: the sub classes constructor possibly did not even start. Special to java is the fact that a method call can lead to an overridden method of a sub class who's constructors has not even passed the super() command.
    My guess now is that you have that some kind of this situation in your code. You create an inner class in a constructor. That inner class calls back a method on the outer class. Now say that the method you are calling is defined in a sub class who's constructor still stucks in super() call. There we are.
    I found a thread in a news group that covers exactly this problem:
    It is therefore a good idea only to call private methods from constructors (that should then also call only private methods). Also if inner classes are created in the constructor then they should not call any non trivial / non private methods of the outer class. Calling overridden methods out of constructors should be avoided strictly!
    Perhaps this has nothing to do with your problem. I cannot tell for sure.
    But this sounds quite interesting.
    Please tell me if my guess was right and if not post simple code the illustrated your problem.
    Here a simple example also throwing NullPointerException:
    class Outer {
      int i = 42;
      abstract class InnerSuper {
        InnerSuper() {
          foo();
        abstract void foo();
      class InnerSub extends InnerSuper {
        void foo() {
          System.out.println(i);
      public void bar() {
        new InnerSub();
      public static void main(String[] args) {
        Outer o = new Outer();
        o.bar();
    } It causes a NullPointerException because the InnerSub constructor did not run. I copied the example from a news group thread i found.
    http://groups.google.de/group/comp.lang.java.programmer/browse_thread/thread/897fba792d689b29/a1ba2ed708636a30?q=inner+class+outer+this+reference+NullPointerException&rnum=4&hl=de#a1ba2ed708636a30
    Here is a even simpler example of strange behavior - even without NullPointerExceptions.
    class A {
         A() {
              System.out.println(getName());
         String getName() {
              return "A";
    class B extends A {
         String NAME = "B";
         String getName() {
              return NAME;
    new B();It will output null instead of B.
    regards
    Sven

  • Private inner class with private constructor

    I read that if constructor is public then you need a static method to create the object of that class.
    But in the following scenario why I am able to get the object of PrivateStuff whereas it has private constructor.
    I am messing with this concept.
    public class Test {
          public static void main(String[] args) {          
               Test t = new Test();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }

    A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
    * Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]
    Your main method is within the body of the top level class, so the type (the inner class) and method are accessible.
    eg:
    class ImInTheSameSourceFileAsInnerAccessTest {
        public static void main(String[] args) {          
            InnerAccessTest t = new InnerAccessTest();
            InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    public class InnerAccessTest {
          public static void main(String[] args) {          
               InnerAccessTest t = new InnerAccessTest();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }Result:
    $ javac -d bin src/InnerAccessTest.java
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    2 errors
    Edited by: pm_kirkham on 20-Jan-2009 10:54 added example of 'in the same source file'

  • Anonymous class - reference to enclosing object

    Hi,
    I have a class (which is in fact an Adapter that implements several interfaces
    for EventListener) that should be instantiated in the code via an anonymous
    class, i.e. like this
    this.addAdapter( new Adapter() {
    // implemented methods here
    Now I have the problem that when I pass the instance of the anonymous class
    later to a method somewhere else, I need a reference to the object which
    instantiated it:
    public class AClass {
    priavte BClass bClass;
    private Adapter adapter;
    public AClass() {
    this.addAdapter( new Adapter() {
    // implemented methods here
    bClass = new BcLass();
    bClass.doSomething
    void addAdpater( Adpater ad ) {
    this.adpater = ad;
    public class BClass {
    public BClass() {
    doSomething( Adapter ad ) {
    // how can I get a reference to the instance
    // of AClass that called this method ?????
    My IDE shows the needed object as member this$0 of the Adpater, so I
    suppose there is some way to get at the reference to this enclosing
    object, but how???
    Thanks in advance for any idea,
    Leif

    If it's possible to get the reference without the adapter explicitly giving it to you, then everything that's been written about read-only adapters is silly, so I would bet that it's not possible.
    Your adapter is written as an inner class, so it has access to all the enclosing object's state. If you can modify the adapter class, you could expose as much of that state as you wanted. Maybe that's as good as the reference for your purposes.
    But maybe not. So the only option I could see is that the adapter itself has a method
    public AClass getEnclosingAClassInstance()
    which returns a reference to the enclosing class. The way to set it might be to make a corresponding set method which AClass calls with 'this' before handing off the adapter to BClass, or by AClass itself providing a getThis method, which the adapter could call. I'm pretty sure you can't get anymore direct access to the enclosing 'this', because the adapter's 'this' shadows it.
    All of which leaves me wondering--why? It's so weird and un-adapter-like that I suspect it's the wrong idiom. But maybe you know something I don't....

  • Help: Factory Class using Inner Class and Private Constructor?

    The situation is as follows:
    I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
    I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
    Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?

    leesiulung wrote:
    As a second look, I was initially confused about your first implementation, but it now makes more sense.
    Let me make sure I understand this:
    - the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
    - the instance() method is the object factory
    - the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
    However, is a private inner class accessible in the outer class? Try it and see.
    How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
    How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
    public interface Game {
        String method();
    public class GameCollection {
        private static  class GameImpl implements Game {
            public String method() {
                return "GameImpl";
        public Game instance() {
            return new GameImpl();
        public static void main(String[] args) {
            GameCollection app = new GameCollection();
            Game game = app.instance();
            System.out.println(game.method());
    }Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game?

Maybe you are looking for