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

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;

  • 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

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

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

  • Error creating an instance of a runnable thread

    I'm trying to create two instances of a runnable thread but get this error message (in Eclipse):
    "No enclosing instance of type GE4000 is accessible. Must qualify the allocation with an enclosing instance of type GE4000 (e.g. x.new A() where x is an instance of GE4000)."
    I don't understand this error at all.
    GE4000 is GE4000.java
    The error occurs here and is within a protected static boolean method.
    for(int t = 0; t < (int) cameraCount; ++t) {
                   streamThreads[t] = new Thread(new CaptureStream(cameraHandle[t], frameBuffers[t], frameCount, basePath));
    CaptureStream Class is defined:
         public class CaptureStream implements Runnable {
    the constructor is:
         CaptureStream(Pv.tHandle handle, Pv.tFrame[] cameraFrames, int frameCount, String basePath) {
    Ironically, within CaptureScreen's run method I do an analogous creation of another thread without seeing an error.
    Edited: I un-nested it and it works! Thanks
    Edited by: Shellback3 on Dec 8, 2010 1:13 PM

    Kayaman wrote:
    I'd recommend avoiding using inner classes or at least learning how to use them before actually using them.I'm new at Java and that's why I posted to the forum.
    Or do you really need to have CaptureStream as an inner class?
    In any case you're trying to create one in a static method, where no enclosing instance of the outer class (GE4000) is available. So at the very least you'd need to make it a static nested class.OK, this is my structure:
    public class GE4000 {
    class CaptureStream implements Runnable {
    run() {}
    boolean startStreamCapture() {}
         public static void main(String[] args) {
    startStreamCapture();
    The method startStreamCapture was static and when I made it to non-static the error went away.
    However I can't use the method in main because it's not static.
    Do I understand correctly that the way to solve this is to put class CaptureStream into CaptureStream.java? That is, un-encapsulate it and then make startStream static?
    BTW My original version extended Thread and it compiled (but didn't do what I wanted) the error cropped up when I changed it to implement runnable.
    I appreciate your help.
    Nate

  • Problem declaring new Class instance

    I would appreciate your help, I am new to programming & decided to learn Java.
    The two programs I have tried to write myself have not compiled for the same error:
    Javac tells me that it cannot resolve the " = new " syntax, it sees NEW as a variable.
    Here is the code for the latest:
    public class DBQuery1 {
         String username, password;
         boolean getOut = false;
    public class PassDB extends javax.swing.JFrame implements ActionListener {
         JTextField uname = new JTextField(10);
         JPasswordField pword = new JPasswordField(10);
         // codePhrase.setEchoChar('*');
         public PassDB() {
              super("duBe's database logon");
              setSize(260, 160);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JPanel pane = new JPanel();
              JLabel unameLabel = new JLabel ("Username: ");
              JLabel pwordLabel = new JLabel ("Password: ");
              JButton submit = new JButton("OK");
              submit.addActionListener(this);
              pane.add(unameLabel);
              pane.add(uname);
              pane.add(pwordLabel);
              pane.add(pword);
              pane.add(submit);
              setContentPane(pane);
              setVisible(true);
              if (getOut == true)
                   PassDB.close();
         public void actionPerformed(ActionEvent evt) {
              PassDB clicked = (PassDB)evt.getSource();
              username = uname.getText();
              password = pword.getText();
              getOut = true;
         public static void main(String[] arguments) {
              PassDB UPass = new PassDB();
    it goes on, but the problem seems to be with the declaration of " UPass ".
    There are other problems with this code that I cannot fix at the moment, but I'll ask those questions when I get this problem fixed.
    Any help will be much appreciated, I know it is something silly I have done, but I can't find the problem myself.
    duBe

    The two programs I have tried to write myself have not
    compiled for the same error:
    Javac tells me that it cannot resolve the " = new "
    syntax, it sees NEW as a variable.It would be interesting to see the error message you are getting - what you have described sounds rather odd - I would expect an error along the lines of "unqualified enclosing instance" or "this can not be referenced from a static context".
    You have declared PassDB as an inner class (it is nested inside another class and is not declared static). As somebody else has already said, if you are new to Java, you might be better not doing that for now.
    To instantiate an inner class, you need an instance of the deepest nested lexically enclosing class. I'm not going to go into detail about that in the New To Java Technology forum, but if you don't already know or understand that, then perhaps inner classes are too much to be tackling right now.
    The syntax for instantiating PassDB is x.new PassDB(), where x is an instance of DBQuery1. Thus new DBQuery1().new PassDB() should compile (though it might not be want you really want). Another option open to you is to use static nested classes - just declare the PassDB class static, and treat it as you would any other class (though now you won't be able to access the non-static fields of DBQuery1 directly)

  • Question about the property of the nested class.

    "Nested classes may be declared static. In this case, the nested class has no reference to an enclosing instance"
    Can any one demonstrate the above through an code example?? thanks

    thanks jverd.
    Then why dont you answer my other thread??You have several threads. I've said what I have tosay in all the ones that I know about, am interested
    in, and have the time to answer. Last one I lookedat, you were in Monica's very capable hands, so I had
    nothing to add.
    Thanks!I may not be the sharpest knife in the drawer, but I know better than to piss of her what's gonna administer the dread Blueberry Pie Torture.

Maybe you are looking for

  • Open popup in dynamic region once region changes flows

    I need to open a popup in a flow if boolean is set to true in the pageFlowScope bean of the dynamic flow bean used in a dynamic region. The parent page/flow is configured in the adfc-config.xml and is controlled by a session bean. So the scenario is

  • TV Remote set-up

    I've an LG model 37 LH 2000. None of the codes in the book work. Anyone got the same problem or know a fix? Regards Tony

  • HT4623 how do you downgrade back to 5.1.1 on a iphone 3gs

    Help

  • Cross tab direction

    Hi friends I want your help in how to change the direction of the cross-tab crystal report to make it suitable for right-to-left languages. When I created a cross-tab report it looks like :-             option1  option2 option3 row-1    XXXX      XXX

  • Business Rule Log

    Error when validating a business rule helfpully suggests checking the log for more details. I have looked around but cannot find the Business rule log. Any ideas where I should look? T, J