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

Similar Messages

  • BUG: Oracle Java Compiler bug with anonymous inner classes in constructor

    The following code compiles and runs just fine using 1.4.2_07, 1.5.0_07 and 1.6.0_beta2 when compiling and running from the command-line.
    It does not run when compiling from JDeveloper 10.1.3.36.73 (which uses the ojc.jar).
    When compiled from JDeveloper, the JRE (both the embedded one or the external 1.5.0_07 one) reports the following error:
    java.lang.VerifyError: (class: com/ids/arithmeticexpr/Scanner, method: <init> signature: (Ljava/io/Reader;)V) Expecting to find object/array on
    stack
    Here's the code:
    /** lexical analyzer for arithmetic expressions.
    Fixes the lookahead problem for TT_EOL.
    public class Scanner extends StreamTokenizer
    /** kludge: pushes an anonymous Reader which inserts
    a space after each newline.
    public Scanner( Reader r )
    super( new FilterReader( new BufferedReader( r ) )
    protected boolean addSpace; // kludge to add space after \n
    public int read() throws IOException
    int ch = addSpace ? ' ' : in.read();
    addSpace = ch == '\n';
    return ch;
    public static void main( String[] args )
    Scanner scanner = new Scanner( new StringReader("1+2") ); // !!!
    Removing the (implicit) reference to 'this' in the call to super() by passing an instance of a static inner class 'Kludge' instead of the anonymous subclass of FilterReader fixes the error. The code will then run even when compiled with ojc. There seems to be a bug in ojc concerning references to the partially constructed object (a bug which which is not present in the reference compilers.)
    -- Sebastian

    Thanks Sebastian, I filed a bug for OJC, and I'll look at the Javac bug. Either way, OJC should either give an error or create correct code.
    Keimpe Bronkhorst
    JDev Team

  • Can't access UIViewRoot from within constructor

    the subject actually says it all: When trying to get the locale over getViewRoot().getLocale the first method returns null. in any other method everything is working. how can i get the viewRoot or load the current locale respectively in the constructor?
    thanks!

    Can't reproduce this problem. It works fine here with latest JSF 1.2.
    Backing bean (request scoped):
    package mypackage;
    import javax.faces.context.FacesContext;
    public class MyBean {
        private String value;
        public MyBean() {
            value = FacesContext.getCurrentInstance().getViewRoot().getLocale().toString();
        public String getValue() {
            return value;
    }JSF page:
    <%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
    <%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
    <!doctype html>
    <f:view>
    <html>
        <head>
            <title>Test</title>
        </head>
        <body>
            <h:outputText value="#{myBean.value}" />
        </body>
    </html>
    </f:view>Output:
    nl_NL

  • Problem with final variables and inner classes (JDK1.1.8)

    When using JDK1.1.8, I came up with following:
    public class Outer
        protected final int i;
        protected Inner inner = null;
        public Outer(int value)
            i = value;
            inner = new Inner();
            inner.foo();
        protected class Inner
            public void foo()
                System.out.println(i);
    }causing this:
    Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
    public Outer(int value)
    ^
    1 error
    With JDK 1.3 this works just fine, as it does with 1.1.8 if
    1) I don't use inner class, or
    2) I assign the value in initializer, or
    3) I leave the keyword final away.
    and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
    Reasons why I am trying to do this:
    1) I can't use a newer JDK
    2) I want to be able to assign the variables value in constructor
    3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
    4) I must be able to use inner classes
    So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?

    You cannot use a final field if you do not
    initialize it at the time of declaration. So yes,
    your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
    public class Outer {
            protected final String str;
            public Outer(String paramStr) {
                    str = paramStr;
                    Inner in = new Inner();
                    in.foo();
            public void foo() {
                    System.out.println("Outer.foo(): " + str);
            public static void main( String args[] ) {
                    String param = new String("This is test.");
                    Outer outer = new Outer(param);
                    outer.foo();
            protected class Inner {
                    public void foo() {
                            System.out.println("Inner.foo(): " + str);
    } producing the following:
    [1:39] % javac Outer.java
    [1:39] % java Outer
    Inner.foo(): This is test.
    Outer.foo(): This is test.
    Is this then an "undocumented feature", working even though it shouldn't work?
    However, I assume you could
    get by with eliminating the final field and simply
    passing the value directly to the Inner class's
    constructor. if not, you'll have to rethink larger
    aspects of your design.I guess this is the way it must be done.
    Jussi

  • Passing Inner class name as parameter

    Hi,
    How i can pass inner class name as parameter which is used to create object of inner class in the receiving method (class.formane(className))
    Hope somebody can help me.
    Thanks in advance.
    Prem

    No, because an inner class can never have a constructor that doesn't take any arguments.
    Without going through reflection, you always need an instance of the outer class to instantiate the inner class. Internally this instance is passed as a parameter to the inner class's constructor. So to create an instance of an inner class through reflection you need to get the appropriate constructor and call its newInstance method. Here's a complete example:import java.lang.reflect.Constructor;
    class Outer {
        class Inner {
        public static void main(String[] args) throws Exception{
            Class c = Class.forName("Outer$Inner");
            Constructor cnstrctr = c.getDeclaredConstructor(new Class[] {Outer.class});
            Outer o = new Outer();
            Inner i = (Inner) cnstrctr.newInstance(new Object[]{o});
            System.out.println(i);
    }

  • Access Parent DC

    How can I access Parent DCs methods in Child DC?
    Suppose I have DC1 is been used in DC2. Now, From DC2 I need to execute methods of DC1 or access an Outplug of DC1.
    Please give me some idea
    thanks in anticipation,
    nikhi∟

    Hi
    1.First place the method you want to expose in DC1 interface controller.
    2. Expose the interface controller as public part in DC1.
    3. Add the public part of Dc1 to Dc2.
    4. Now add the InterfaceComponentController of DC1 in DC2 .
    5. Now you should be able to access to methods in Dc1 interface controller.
                                                                                    6.to access outbound plug just writ
    wdThis.wdget<interfacecontollername>().wdFireplug<outplugname>();
    I am new to webdynpro java up to my knowledge i answered the question if it useful give me points

  • Inner Classes Changing Access Rights Of Parent  Members

    I read that if you access a parent class's private memebers or methods from within an inner class, those members of methods will automatically and silently be converted to having package access. This seems dangerous and I'd like to know how I could design around it.
    Here is my current dilemma. I have an EventHandler class whose handleEvent() method changes with the object's state. I've implemented this using the Strategy Pattern, where the Strategy objects are inner classes of EventHandler. The problem is that these Strategy objects need access to certain private members and methods of their parent. There is no reason, however, to give package access to these members and methods. What can I do? Or does this suggest that I need a design change? Other than this issue, though, I'm quite happy with the design.
    Thanks for any thoughts,
    John

    When inner classes access private fields or methods, the compiler generates new package-private methods
    with names like "access$000":
    import java.lang.reflect.*;
    public class X {
        private void x() {}
        class Y {
            public void y() {
                x();
        public static void main(String[] args) {
            Method[] methods = X.class.getDeclaredMethods();
            for(int i=0; i<methods.length; ++i)
                System.out.println(methods.getName());
    So it's not correct that the access to fields or methods is changed, just that additional methods are added.
    Unless you're in the habit of writing method names that contain '$', I think it's unlikely that you'll directly call
    these new methods, and if you do, it should be easy to spot!

  • Why only final variables can be accessed in an inner class ?

    Variables declared in a method need to declared as final if they are to be accessed in an inner class which resides in that method. My question is...
    1. Why should i declare them as final ? What's the reason?
    2. If i declare them as final, could they be modified in inner class ? since final variables should not modify their value.

    (Got an error posting this, so I hope we don't end up with two...)
    But what if i want to change the final local variable within that method instead of within anonymous class.You can't. You can't change the value of a final variable.
    Should i use same thing like having another local variable as part of method and initializing it with the final local variable?You could do. But as in the first example I posted you are changing the value of the nonfinal variable not the final one. Because final variables can't be changed.
    If so, don't you think it is redundant to have so many local variables for so many final local variables just to change them within that method?If you are worried that a variable might be redundant, don't create it. If you must create it to meet some need then it's not redundant.
    Or is there any alternate way?Any alternate way to do what?

  • Local variable can't be accessed from inner class ???????? Why ??????

    Plesae help, help, help. I have no idea what to do with this bug.........
    <code>
    for ( int i = 0; i <= 2; i++ ) {
    for ( int j = 0; j <= 2; j++ ) {
    grids[i][j] = new MyButton ();
    grids[i][j].setBorder(but);
    getContentPane().add(grids[i][j]);
    MyButton sub = grids[i][j];
    sub.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if ( sub.getState() == 0 ) {
         sub = new MyButton( (Icon) new ImageIcon(imageFile));
         if ( imageFile.equals("cross.jpg") ) {
              sub.changeState(1);
         else {
              sub.changeState(2);
    </code>
    The compiler complains that "sub" is in the inner class, which is the ActionListener class, must be declared final. Please tell me what to do with it. I want to add an ActionListener to each MyButton Object in the array. Thanks ......

    OK, now I changed my code to this :
    for ( int i = 0; i <= 2; i++ ) {
      for ( int j = 0; j <= 2; j++ ) {
        grids[i][j] = new MyButton ();
        grids[i][j].setBorder(but);
        getContentPane().add(grids[i][j]);
        grids[i][j].addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if ( grids[i][j].getState() == 0 ) {
               grids[i][j] = new MyButton( (Icon) new ImageIcon(imageFile));
              if ( imageFile.equals("cross.jpg") ) {
               grids[i][j].changeState(1);
              else {
              grids[i][j].changeState(2);
    [/cpde]
    Thanks for your advice !!!!!!
    Now the compiler says that i and j are local variables accessed from inner classes, needs to be declared final. How can I solve this then ???

  • Why eclipse gives me warning if I access in inner class a parent  field ?

    I have a class
    class A{
    private Map fValues;
    A(){
    fValues= new HashMap();
    prrotected class B {
    B(){
    fValues.get("String");
    Above class is only for an example to expalin my problem.
    Inner class B wants to access fValues from class A .
    The eclipse gives me a warning
    Access to enclosing method fValues from the type A is emulated by a synthetic accessor method. Increasing its visibility will improve your performance
         I order to get rid of this warning I must make fValues public is this the only solution ?
    miro

    miro_connect wrote:
    I have a class
    class A{
    private Map fValues;
    A(){
    fValues= new HashMap();
    prrotected class B {
    B(){
    fValues.get("String");
    Above class is only for an example to expalin my problem.
    Inner class B wants to access fValues from class A .
    The eclipse gives me a warning
    Access to enclosing method fValues from the type A is emulated by a synthetic accessor method. Increasing its visibility will improve your performance
         I order to get rid of this warning I must make fValues public is this the only solution ?
    miroWhat happens if you remove the modifier? (That is uses default)

  • 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

  • How to access var in outter class inside inner class

    I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
    import java.io.*;
    public class Kalkulator1{
    int number1,number2,x;
    /* The short way to create instance object for input console*/
    private static BufferedReader stdin =
    new BufferedReader( new InputStreamReader( System.in ) );
    public static void main(String[] args)throws IOException {
    System.out.println("---------------------------------------");
    System.out.println("Kalkulator Sayur by Cumi ");
    System.out.println("---------------------------------------");
    System.out.println("Tentukan jenis operasi bilangan [0-4] ");
    System.out.println(" 1. Penjumlahan ");
    System.out.println(" 2. Pengurangan ");
    System.out.println(" 3. Perkalian ");
    System.out.println(" 4. Pembagian ");
    System.out.println("---------------------------------------");
    System.out.print(" Masukan jenis operasi : ");
    String ops = stdin.readLine();
         int numberops = Integer.parseInt( ops );
    System.out.print("Masukan Bilangan ke-1 : ");
    String input1 = stdin.readLine();
    int number1 = Integer.parseInt( input1 );
    System.out.print("Masukan Bilangan ke-2 : ");
    String input2 = stdin.readLine();
    int number2 = Integer.parseInt( input2 );     
         Kalkulator1 op = new Kalkulator1();
    Kalkulator1.option b = op.new option();
         b.pilihan(numberops);
    System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
    class option{
    int x,y;
         int number1 = Kalkulator1.this.number1;
         int number2 = Kalkulator1.this.number2;
    void pilihan(int x) {
    if (x == 1)
    {System.out.println("Operasi yang digunakan adalah Penjumlahan");
            int y = (number1+number2);
            System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
             int y = (number1-number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
             int y = (number1*number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
             int y = (number1/number2);
             System.out.println("Hasil dari operasi adalah =" + y);}
    else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
    }

    Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
    In future place code tags around your code to make it retain formatting. Highlight code and click code button.

  • Accessing method in an inner class

    I have a class, which has an Inner Class, which is an extension of AbstractTableModel. The extended TableModel class has a new method, so it looks something like this;
    public class TheOuterClass
        JTable aTable
        TableModel theTableModel
        public initTable
             theTableModel = new MyTableModel();
         public TableModel getModel()
             return theTableModel;
         private class MyTableModel extends AbstractTableModel
                public void myTableModelMethod()
    }So, the idea here is that I have a class that has a table referenced by 'aTable', which uses MyTableModel as the class for it's table model. I have only implemented the basics here. The class also has a method called getModel(), so from a reference to 'TheOuterClass', I can access the table model.
    Now, say I have a reference to TheOuterClass called toc, and I want to access my new method in the table model;
    toc.getModel().myTableModelMethod()The above won't work, because getModel() returns a type of TableModel.
    My question then is how do I cast this to the correct type, so I can access the method 'myTableMethod()'?
    Is for example, the following a legal possibility, because I cannot seem to make it work;
    (toc.getModel().getClass())(toc.getModel()).myTableMethod();The quick fix, I guess is to correct getModel in TheOuterClass, so it returns the correct type, but I am hoping to not do this. (This is part of a larger piece of code obviously, and TheOuterClass is in reality a bean, and I don't wnat to disturb anymore than I have to).
    Any suggestions / ideas would be gratefully appreciated

    You are of course both correct, the class is private, should have spotted that! Doh. Also correct in that this is 'not the most elegant design', but you know the way it is you have to work with what you are given.
    So, I changed the class to public....
    What I had hoped is that the following would work
    ((toc.getModel().getClass())(toc.getModel())).myTableMethod()get a reference to the table model
    (toc.getModel())cast it to the correct type (not sure if this is a valid way to cast??)
    ((toc.getModel().getClass())(toc.getModel()))then call the method.
    This does not compile, it complains about a missing ')', and I'm sure they are all there. My question here then is, Is this a valid way to cast, now that the inner class is public?
    As to why I want to do this, then some explanation is required;
    The table model holds a Vector with all the data in it, some which is not actually in the table (it was originally written this way). My additional method myTableMethod() is intended to help access the data that is not shown in the table.
    Coming back to kajbj's point of creating an interface, I presume what is being suggested is that I create a public interface with the myTableMethod() in it, and make myTableModel implement this interface. Since the interface is public, then I can cast to that. Is this what you meant?
    Thanks for your help so far

  • How to refer the parent class object from an inner class

    Hi,
    I have a class X, which contains an inner private class Y. Class X has a method getY which returns an object of class Y. Class Y has a method getParent. I want to return the object of parent class from this. The code is like this:
    public inerface IY;
    public class X {
    private class Y implements IY {
    public getParent {
    // ... return the object of parent class which created the object of this inner class
    public IY getY() {
    return new Y();
    Can somebody help me with this...

    interface IY {
    public class X {
        private class Y
            implements IY {
            private X parent;
            public Y(X x)
                parent = x;
            public X getParent()
                // ... return the object of parent class which created the object of this inner class
                return parent;
        public IY getY()
            return new Y(this);
    }Filip

  • Accessing member variable within an anonymous inner class

    I'm getting a compiler error with the following snippet which resides in a constructor (error below):
            final String fullNamesArr[] = new String[ lafsArr.length ];
            String lafNamesArr[] = new String[ lafsArr.length ];
            JMenuItem namesMenuItemArr[] = new JMenuItem[ lafsArr.length ];
            for ( int i = 0 ; i < lafsArr.length ; i++ )
                StringTokenizer tokenizer;
                fullNamesArr[ i ] = lafsArr[ i ].getClassName();
                tokenizer = new StringTokenizer( fullNamesArr[ i ] );
                while ( tokenizer.hasMoreTokens() )
                    lafNamesArr[ i ] = tokenizer.nextToken( "." );
                namesMenuItemArr[ i ] = new JMenuItem( lafNamesArr[ i ] );
                lafMenu.add( namesMenuItemArr[ i ] );
                namesMenuItemArr[ i ].addActionListener(new ActionListener()
                        public final void actionPerformed(final ActionEvent e)
                            String actionCommand = e.getActionCommand();
                            int iCount = 0;
                            for ( int index = 0 ; index < fullNamesArr.length ; index++ )
                                if ( fullNamesArr[ index ].contains( actionCommand ))
                                    iCount = index;
                                    break;
                            System.out.println( "Setting LAF to '" +
                                                fullNamesArr[ iCount ] + "'" );
                            try
                                UIManager.setLookAndFeel( fullNamesArr[ iCount ] );
                            catch ( UnsupportedLookAndFeelException ulafe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Not a valid LAF class." );
                            catch ( ClassNotFoundException cnfe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Class not found." );
                            catch ( InstantiationException ie )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Can't instantiate class." );
                            catch ( IllegalAccessException iae )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Illegal access." );
    DBBuilder.java:1280: cannot resolve symbol
    symbol : method contains (java.lang.String)
    location: class java.lang.String
    if ( fullNamesArr[ index ].contains( actionCommand ))
    ^
    1 error
    BUILD FAILED
    My question: Why can I access fullNamesArr in other spots in the anon-inner class,but not with the String.contains() method? BTW, the carrot is under the left bracket '['.
    TIA,
    Jeff

    My question: Why can I access fullNamesArr in other
    spots in the anon-inner class,but not with the
    String.contains() method? BTW, the carrot is under
    the left bracket '['.You're misinterpreting the message. The problem is not your variable fullNamesArr, but rather the method contains(java.lang.String). Since that method was only added in Java 5 (aka 1.5) you might look if you're compiling with JDK 1.4 or earlier.

Maybe you are looking for