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.

Similar Messages

  • 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;

  • Enclosing instance

    I've never seen this error before. I was trying to create a instance of an inner-class. The code is declared like this:
    static ShuttleController shuttleControl;Then it is created in the main Method like this:
    shuttleControl = new ShuttleController();I'm using eclipse to program this code and it gave me this error:
    No enclosing instance of type SpacePanel is accessible. Must qualify the allocation with an enclosing instance of type SpacePanel (e.g. x.new A() where x is an instance of SpacePanel).This is the code for the class ShuttleControlle:
    class ShuttleController implements Runnable
              public ShuttleController()
              public void run()
                   shuttle.update(WIDTH/2, HEIGHT/2, rotation);
                   xPos += xMom;
                   yPos += yMom;
         }This class is an inner-class in the class SpacePanel

    Objects of an "inner class" can access the instance of the enclosing class and its fields; therefore, they must have an implicit reference to the enclosing object, and cannot be instantiated in static context.
    Maybe you are looking for a "nested class" instead, which does not have a reference to the enclosing object. To do that, you add the "static" keyword:
    static class ShuttleController implements RunnableEdited by: spoon_ on Dec 15, 2007 10:21 PM

  • How to refer to enclosing instance from within the member class?

    Hi
    How to refer to the enclosing instance from within the member class?
    I have the following code :
    import java.awt.*;
    import java.awt.event.*;
    public class MyDialog extends Dialog
         public MyDialog(Frame fr,boolean modal)
              super(fr,modal);
              addWindowListener(new MyWindowAdapter());
         public void paint(Graphics g)
              g.drawString("Modal Dialogs are sometimes needed...",10,10);
         class MyWindowAdapter extends WindowAdapter
              public void windowClosing(WindowEvent evt)
                   //MyDialog.close(); // is this right?
    In the above code, how can I call the "close()" method of the "Dialog" class (which is the enclosing class) from the inner class?
    Thanks in advance.
    Senthil.

    Hi Senthil,
    You can directly call the outer class method. Otherwise use the following way MyDialog.this.close(); (But there is no close() method in Dialog!!)
    If this is not you expected, give me more details about problem.
    (Siva E.)

  • 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();
    }

  • No enclosing instance of the type AClass is accessible in scope

    Hi all,
    Below is a file that defines AClass and CClass. I was told to use the construction CClass toRet = (CClass) AClass.this.createDClass(); in method method in CClass, but I can't get it to work. I get the message "No enclosing instance of the type AClass is accessible in scope". What does this mean? What does "(CClass) AClass.this.createDClass()" mean, I have never seen that type of call before?
    public class AClass extends BClass {
    public AClass(int id, AClassInit initInfo,
    String host, Integer port) {
    super(id, initInfo, host, port);
    public DClass createDClass() {
    return new CClass();
    class CClass extends DClass {
    private AClassInit AClassInit = null;
    public CClass() {
    super();
    private CClass method() {
    CClass toRet = (CClass) AClass.this.createDClass();
    return toRet;
    Thanks
    Markus

    CClass should be an inner class of AClass in order that
    (CClass) AClass.this.createDClass() work

  • No enclosing instance of type Foo is accessible

    i m trying to access class within a class it is giving this error
    No enclosing instance of type Foo is accessible. Must qualify the allocation with an enclosing instance of type Foo (e.g. x.new A() where x is an instance of Foo).what does this mean and i can make it correct...??

    my class file is
    public class a{
       public class b{
       public class c{
    }and jsp page where i want to access class b
    a.b initialize = new a.b();in my jsp page it is giving error :
    No enclosing instance of type LanguageTranslate is accessible. Must qualify the allocation with an
    enclosing instance of type LanguageTranslate (e.g. x.new A() where x is an instance of
    LanguageTranslate).

  • I need help on enclosing instance.

    This is the part of code i am having trouble with:
    SkillUse skilluse = new SkillUse();
    SkillUse.SkillTimer skilltimer = new SkillUse.SkillTimer(skilluse, skillinstance, 67, j7);
    This is the error:
    an enclosing instance that contains SkillUse.SkillTimer is required.
    Then I searched forum and changed to this form:
    SkillUse skilluse = new SkillUse();
    SkillUse.SkillTimer skilltimer = skilluse.new SkillUse.SkillTimer(skilluse, skillinstance, 67, j7);
    Then I still gets error saying this:
    '(' expected
    SkillUse^.SkillTimer(skilluse, skillinstance, 67, j7);
    I am lost at this point and I am novice at java.
    Can anyone tell me how I can fix this problem?
    Message was edited by:
    yeo123
    Message was edited by:
    yeo123

    The smartest thing to do would be to add a factory method in the outer class:
    public class SkillUse {
        public class Timer {
           private  Timer(String etc){}
        public Timer newTimer(String etc) {
            return new Timer(etc);
        public static void main(String[] args) {
            //demo:
            SkillUse use = new SkillUse();
            SkillUse.Timer timer = use.newTimer("etc...");
    }Also, in the code you gave, do you really want to pass the outer instance
    to the inner constructor? That is redundant.

  • Enclosing instance error...help

    I have this error in my program and I have no idea how to fix it, it even has my Java Professor stumped.
    RaceSort.java [56:1] an enclosing instance that contains Rectangle2D.Double is required
    Shape s = new Rectangle2D.Double(x,y,barwidth,(height-y));
    I have java.awt.geom.* imported and I don't have any other mentions of Shape or Rectangle2D.Double elsewhere in the program.
    Thanks,
    PJ

    first of all i m not sure you know what u r doing after seeing this code.
    what "java proffesor" looked at that?????????
    in order to fix this you first must understand a few things
    1. Shape s = new Rectangle2D.Double(x,y,barwidth,(height-y));
    because you created a Rectangle2D object in your file, this is the one being used and its not implemeting
    Shape therefore you can not do Shape s = new Rectangle2D.
    2. If you wanted to used the genom Rectangle2D removed you code of the Rectangle2D class from your file.
    3. if you do want to use your own Rectangle2D class you need to implement Shape, Double must be a public static class with a non empty constructor which receives the 4 variables but i'd suggest using genom.Rectangle2D
    4. there is no public class in the file. try writing public class RaceSort and not class RaceSort.
    after you do all that fix the code (naturally i didn't start fixing this because i didn't even bother seeing what u r trying to do, cause all of the mess) and if then u still have errors publish the code again.

  • 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.

  • "No enclosing instance accessible." ?

    I have a public class with a static method and a static field (and other non-static stuff):
    public class A ...
    static private MyCache  mc = null;
    static public String getText(...) {
         mc = new MyCache(); //doesn't compile
    }but I can't instantiate the object in my static method :
    "No enclosing instance of type A is accessible. Must qualify the allocation with an enclosing instance of type A (e.g. x.new A() where x is an instance of A)."
    Well, this method is static because it doesn't need an instance of A. As MyCache is static. So I don't understand this ...

    Yes ... after I changed it to static, too it worked.
    Never had a situation before that I needed to make an
    inner class static ...Well, now you had one. Non-static inner classes are indeed non-static and only exist within an instance of the enclosing class. :)

  • Access enclosing Instance at runtime

    I try to create a general Method to get a new Instance of a given Object:
    class A {
         public B b = new B();
         public class B {
    public class SpeedTest {
         public static Object getMeANew(Object o) {
              Class c = o.getClass();
              try {
                   return c.newInstance();
              } catch (Exception e) {               
                   e.printStackTrace();
              return null;          
         public static void main(String[] args) {               
              A a = new A();
              Object obj = getMeANew(a);  // this is just fine
              obj = getMeANew( ((A)obj).b); // runtime error
    }I can't create an Instance of B at runtime.
    I played with the new method and got this:
            public static Object getMeANew(Object o) {
              Class c = o.getClass();
              Class decl = c.getDeclaringClass();
              if (decl != null) {
                   Constructor cons = null;               
                   try {
                        cons = c.getConstructor(decl);
                   } catch (Exception e) {               
                        e.printStackTrace();
                   try {
                        return cons.newInstance(decl.newInstance());  // << problem
                   } catch (Exception e) {               
                        e.printStackTrace();
              } else {          
                   try {
                        return c.newInstance();
                   } catch (Exception e) {               
                        e.printStackTrace();
              return null;          
         }But this is not a full solution consider this example:
    class A {
         public int value;
         public B b = new B();
         public class B {
              public void print() {
                   System.out.println(value);
            public static void main(String[] args) {               
              A a = new A();
              a.value = 100;
              a.b.print();  // << prints 100
              a.b = (A.B)getMeANew(a.b);
              a.b.print(); // << prints 0
         }I want that both print() result in '100' so i'am looking for something like:
    cons.newInstance(o.getEnclosingInstance());   // << Something that don't require a new field in every ObjectIs this possible ?

    Nobody has a solution?
    What is the qualified name to access the enclosing class instance (i.e. the "this$0" member)?
    Or, for the code snippet below, what is the qualified name for the getEnclosingClass() method?
    public class Foo
        int i = 42 ;
        public class Bar { }
        public static Object getEnclosingClass(Object o)
         try { return o.getClass().getDeclaredField("this$0").get(o) ; }
         catch (NoSuchFieldException x) {}
         catch (IllegalAccessException x) {} ;
         return null ;
        public static void main(String[] args)
         Foo foo = new Foo() ;
         Bar bar = foo.new Bar() ;
         System.err.println(((Foo)getEnclosingClass(bar)).i) ;
    }thx for assistance!

  • Scriptlet - can't change bean instance reference?

    I am having trouble assigning a reference of a bean to an entirely new object.
    What I am trying to do here is replace my cartDetailBean with a de-serialized version from the database.
    I have written a utility class called BlobTool which returns an Object. In this case, I expect the Object to be of type CartBean.
    <jsp:useBean id="cartDetailBean" class="com.abctech.myapp.CartBean" scope="page"/>
    <jsp:useBean id="blobBean" class="com.abctech.myapp.util.BlobTool" scope="page"/>
    <%
    //Use a temporary cartBean in the scope of the request to inspect it's contents.
    cartDetailBean = (com.abctech.myapp.CartBean)
              blobBean.getBlobFromTable("orders",
    "serialized_order",
    "orderid",
    request.getParameter("orderid").toString());                                             
    %>After this I try to access the cartDetailBean in JSTL and I get empty values, for example:
    <c:out value="${cartDetailBean.customerID}"/>Has none of the values of the CartBean returned by blobBean.getBlobFromTable(...).
    How can I put a bean into scope such that I can access it conveniently with JSTL tags?

    Well you put java code where it is supposed to be. In a servlet or a java bean.
    You put that java code in a servlet, set the request attribute(s) and then forward to the jsp to display the result.
    Only one of those parameters to the method is dynamic.
    You could write a helper class so that JSTL could access that better.
    something like
    public class CartHelper{
      String orderId;
      public String getOrderId(){ return orderId; }
      public void setOrderId(String orderId){this.orderId = orderId;}
      public CartBean getCart(){
        BlobTool blobBean = new BlobTool();
        CartBean cartDetailBean = (CartBean)
              blobBean.getBlobFromTable("orders",
    "serialized_order",
    "orderid", orderId);
        return cartDetailBean;
    }and then in JSP:
      <jsp:useBean id="helper" class="com.abctech.myapp.CartHelper"/>
      <c:set target="helper" property="orderId" value="${param.orderid}"/>
      <c:set var="cartDetailBean" value="${helper.cart}"/>
    This approach
    - removes scriptlet code from your JSP
    - removes the details of blob access, and which tables to access from the jsp
    - lets you use JSTL in a semi-neat way
    Cheers,
    evnafets

  • Why appears - "Static member 'varName' accessed via instance reference" ?

    Hi!
    I use static variable in other class and get this warning. Why appears this warning?

    It's a warning that you might be doing something wrong. If you access a static variable you should for clarity (to prevent you from misunderstandings) do so by the name of the class in which it is defined, not by one of the instances of that class.

  • Subform reference (instance/index)

    I have two drop-down boxes in a subform.  When item in first drop-down is selected, items in second drop-down are limited (see example below).  My problem is when multiple instances of the subform exist, the first drop down will only apply to the first instance of the form.  Is there a way to be more specific in a subform row/instance reference?  I want to change the item in the current row or current instance of subform.
    Example: 
    1st Drop-down     2nd Drop-down
    US                     New York or Washington (choose one)
    France                Paris or St. Martin (choose one)  
    Thanks

    This image illustrates my problem.  This table is actually a series of subforms.  When a new instance is added, the user can choose a different region and then a state within the region.  My problem is as rows/subforms are added I can't get the code to refer to the appropriate instance.  It will only refer to the first instance and no new instances.

Maybe you are looking for

  • Line item display in FS10n

    During our configuration days, we have set the Line Item Display indicator in all our GL accounts (ex, Sales account). Details of our SALES transactions in FS10n are posted by document, per material per profit center (same material and profit center,

  • TS1717 iTunes app on iPhone and iPad too slow to use since 5.1 update

    The iTunes store app on my iPad and iPhone 4s take about a minute per instruction to load, which sadly makes purchases not possible to be carried out.

  • Programatically show/hide step types in the Steps pane

    When a user on a new Teststand Development bench syncs to a central repository of custom Teststand components and supporting LabVIEW code, I would like to expose only custom step types saved in myTpes.ini in the steps pane. None of the standard step

  • Suitcase Fusion 3 for fonts slowing down Illustrator?

    I'm working on a PC in windows 7 and using CS5. I have Extensis Suitcase Fusion 3 for font management but someone told me that this may be why my Illustrator in particular is so slow. I frequently have to sit and wait for it to catch up to me while t

  • Object Library/PL-Sql Library Use?

    1. I would like to know the benefits of the new concepts like Object library and Object Group etc. All I gather is that they can be subclassed, the advantage of this being, I need to change only at one place, and it replicates in rest of the programs