Extending a member inner class

I have a class
public class A{
class InnerClassB{
Now the question is how to extend the inner class would it be
class ExtendingInnerClassB extends A.B{
or else?
I am not sure anybody knows?

Regarding inheritance from inner classes you must define your constructor:
public ExtendedInnerClass(EnclosingClass EC) { EC.super(); }
why?????
well
1. Where is the handle? The handle is an internal thing which is designed to accept the enclosing class. It is something which is not in the programmer's control. when there is an inner class, it is natural that the inner class cannot exist without its outer class. And that is the reason why the instantiation of an inner class is done using new OuterClass().new Innerclass(). U can see that the innerClass object is created based on the outer class object (assuming that the inner Class is not static). I hope that this is clear. Now .. the whole point is how does the compiler know that the Outerclass is the enclosing class? When the above line is compiled, the tricky handle in the inner class is assigned to the Outer class. So any reference henceforth is made based on this handle.
2. In the Inherited Inner class, there is no way to assoicate the handle in the above manner. Hence we are forcing by calling the super().
3 Otherwise why not simply create with: new InheritedInnerClass(EnclosingClass)? This is not possible. What if the inherited inner class needs a constructor in the above manner. That is assume that there is a class A. Then if the Inner Class needs the constructor to be InnerClass(A a, EnclosingClass b) for some other purpose, then what judgement can the compiler take? So that answers the question <b>Can't the compiler compile the inherited inner class assuming a handle to the enclosing class and then force an instance to be created using the EnclosingClass.new syntax?</b> Becuase in this case it cant go by any assumption.
4. Maybe the compiler designers can make some change such that the inherited inner class should have all its constructors beginning with the enclosing object and there should be atleast one constructor. But somehow I feel that it is too much of asking.

Similar Messages

  • Inner class instantiation

    Compiling the following code gives me error
    public class A
      public A()
      boolean a=true;
      class B
      { // removed syntax error "Inner"
        B()
          a = false;
      public static void main(String [] arg)
        A a = new A();
        A.B ab = a.new A.B();
        System.out.println(a);
    }The error I get is
    "A.java": Error #: 200 : '(' expected at line 30, column 21
    could somebody advise me as what I am doing wrong??

    this will compile
    public class A
    public A()
    boolean a=true;
    static class B
    { // removed syntax error "Inner"
    boolean a;
    B()
    a = false;
    public static void main(String [] arg)
    A a = new A();
    B ab = new A.B();
    System.out.println(a);
    I was talking about a member inner class. Thanx anyway. Yahya's solution worked. Interesting thing is that the way I was instantiating it is mentioned in Java Sun Certified Programmer Book in Inner classes chapter. by Syngress. But that definitely seems to be a mistake.

  • Cann't extend a inner class where as can Implement a nested Interface

    i cann't extend a inner class in some other outer class . Where as i can implement the nested Interface in some other class. Why????
    for example:-
    class ABC
    class Inner
    /* class body */
    interface TempInterface
    /* interfacebody */
    class OuterClass
    class InnerTwo extends ABC.inner //(line 1)Will give error
    class InnerTwo implements ABC.TempInterface //(line 2)Will run fine
    the line 1 is going to give compilation error i.e not in the scope but the line 2 will run fine .
    Both of the things are in the same class but giving 2 other results.
    I am not getting sufficient reasons for it.
    Can any one help me????
    Reagrds
    Arunabh

    As far as the language is concerned, the classonly
    exists in the context of an instance of theenclosing
    class.This still exhibits a class/object confusion to me.
    It should be 'instance only exists ...' or 'instance
    can only exist'. The class only exists in the
    scope of the enclosing class, but this is another
    issue.I'm not following what you're saying. The second sentence sounds like you're disagreeing with me. The last sentence sounds like you're agreeing with me.
    A non-static nested class is an instance member, just like an instance method or instance variable. As such, as far as the language is concerned, that class only exists in the context of an instance of the enlcosing class.It's not just instances of the nested class--its the class definition itself that only exists within the context of an instance of the enclosing class. That's why you have to do anEclosingIntstance.NestedClass and can't do EnclosingClass.NestedClass.

  • Inner Class extending the outer class

    Could anyone explain this code to me? It can compile and run. Could anyone tell me what the class Main.Inner.Inner is? What members does it consists of? How the compiler manage to build such a class?
    public class Main {
        public static class Inner extends Main {
        public static void main(String[] args) {
            System.out.println("Hello, world.");
    }

    By the way, it's not really an inner class, because it's static. It's just a nested class.
    You might want to have a nested class extend its enclosing class if, maybe, you wanted to delegate to subclasses and didn't want to create a lot of extra source code files, which might make sense if the nested subclasses were really small.
    public abstract class Animal {
      public abstract void makeSound();
      private Animal() {} // can't be directly instantiated
      private static class Dog extends Animal {
        public void makeSound() { System.out.println("woof"); }
      private static class Cat extends Animal {
        public void makeSound() { System.out.println("meow"); }
      private static class Zebra extends Animal {
        public void makeSound() { System.out.println("i am a zebra"); }
      public static Animal get(String desc) {
        if ("fetches sticks".equals(desc)) {
          return new Dog();
        if ("hunts mice".equals(desc)) {
          return new Cat();
        if ("stripey horse".equals(desc)) {
          return new Zebra();
        return null;
    public class AnimalTest {
      public static void main(String... argv) {
        Animal a = Animal.get("fetches sticks");
        a.makeSound();
    }

  • I don't understand the design of inner class private member

    This is a question about the java language specification of inner classes.
    In the java langage specification document, we read
    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.
    This allows following code :
      public class PrivateTest {
        public PrivateTest()
          Hello hello = new Hello();
          System.out.println(hello.secret);
        class Hello
           private String secret = "This is a secret";
      } wherein accessing the private secret field is allowed
    from into the PrivateTest enclosing class.
    My questions are :
    a) It seems that private methods or constructors of
    inner classes have no meaning, we could also declare
    them as public. True or false ?
    b) Is there any reason that Java bypass this private
    mechanism ?
    c) Why is the above definition not written with
    "first enclosing" instead of "top level" ?
    Thanks in advance

    Private methods and constructors of an inner class can only be accessed within the outer class. Other classes can't instantiate it or use the private methods.
    You can also make your inner class private, so it is not possible to refer to the class from outside (and thereby another way of preventing it from being instantiated).
    So it does matter which access modifiers you use.
    I think top level is more precise than first enclosing, because you can have inner classes in inner classes, which are still available for the top level class (haven't tested this).

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

  • HELP: Inner Class vs. Private Member

    I use "javadoc -private" to create documents with inner classes. As a result, all private fields and methods, which I don't need, show up in the same document. Is there any way I can have inner classes without private members?

    how do you declare your inner class?
    Is it (public)
    public static class MyInnerClassor (private)
    private static class MyInnerClassor (package)
    static class MyInnerClassor (protected)
    protected static class MyInnerClassTry to change the way you declare the inner class. Use protected or package or public instead.

  • Null pointer exception with inner class

    Hi everyone,
    I've written an applet that is an animation of a wheel turning. The animation is drawn on a customised JPanel which is an inner class called animateArea. The main class is called Rotary. It runs fine when I run it from JBuilder in the Applet Viewer. However when I try to open the html in internet explorer it gives me null pointer exceptions like the following:
    java.lang.NullPointerException      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2761)      
    at sun.java2d.SunGraphics2D.drawImage(SunGraphics2D.java:2722)      
    at Rotary$animateArea.paintComponent(Rotary.java:251)      
    at javax.swing.JComponent.paint(JComponent.java:808)      
    at javax.swing.JComponent.paintWithOffscreenBuffer(JComponent.java:4771)      
    at javax.swing.JComponent.paintDoubleBuffered(JComponent.java:4724)      
    at javax.swing.JComponent._paintImmediately(JComponent.java:4668)      
    at javax.swing.JComponent.paintImmediately(JComponent.java:4477)      
    at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:410)      
    at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:117)      
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:178)      
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:448)      
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)      
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)      
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)      
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    Do inner classes have to be compiled seperately or anything?
    Thanks a million for you time,
    CurtinR

    I think that I am using the Java plugin ( Its a computer in college so I'm not certain but I just tried running an applet from the Swing tutorial and it worked)
    Its an image of a rotating wheel and in each sector of the wheel is the name of a person - when you click on the sector it goes red and the email window should come up (that doesn't work yet though). The stop and play buttons stop or start the animation. It is started by default.
    This is the code for the applet:
    import java.applet.*;
    import javax.swing.JApplet;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.image.*;
    import java.util.StringTokenizer;
    import java.net.*;
    public class Rotary extends JApplet implements ActionListener, MouseListener
    public boolean rotating;
    private Timer timer;
    private int delay = 1000;
    private AffineTransform transform;
    private JTextArea txtTest; //temp
    private Container c;
    private animateArea wheelPanel;
    private JButton btPlay, btStop;
    private BoxLayout layout;
    private JPanel btPanel;
    public Image wheel;
    public int currentSector;
    public String members[];
    public int [][]coordsX, coordsY; //stores sector no. and x or y coordinates for that point
    final int TOTAL_SECTORS= 48;
    //creates polygon array - each polygon represents a sector on wheel
    public Polygon polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
    polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
    polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
    polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
    polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48;
    public Polygon polySectors[]={polySector1,polySector2,polySector3, polySector4, polySector5,polySector6,polySector7,polySector8,polySector9,polySector10,
                      polySector11,polySector12,polySector13,polySector14,polySector15,polySector16,polySector17,polySector18,polySector19,polySector20,
                      polySector21,polySector22,polySector23,polySector24,polySector25,polySector26,polySector27,polySector28,polySector29,polySector30,
                      polySector31,polySector32,polySector33,polySector34,polySector35,polySector36,polySector37,polySector38,polySector39,polySector40,
                      polySector41,polySector42,polySector43,polySector44,polySector45,polySector46,polySector47,polySector48};
    public void init()
    members = new String[TOTAL_SECTORS];
    coordsX= new int[TOTAL_SECTORS][4];
    coordsY= new int[TOTAL_SECTORS][4];
    currentSector = -1;
    rotating = true;
    transform = new AffineTransform();
    //***********************************Create GUI**************************
    wheelPanel = new animateArea(); //create a canvas where the animation will be displayed
    wheelPanel.setSize(600,580);
    wheelPanel.setBackground(Color.yellow);
    btPanel = new JPanel(); //create a panel for the buttons
    btPanel.setLayout(new BoxLayout(btPanel,BoxLayout.Y_AXIS));
    btPanel.setBackground(Color.blue);
    btPanel.setMaximumSize(new Dimension(30,580));
    btPanel.setMinimumSize(new Dimension(30,580));
    btPlay = new JButton("Play");
    btStop = new JButton("Stop");
    //txtTest = new JTextArea(5,5); //temp
    btPanel.add(btPlay);
    btPanel.add(btStop);
    // btPanel.add(txtTest); //temp
    c = getContentPane();
    layout = new BoxLayout(c,layout.X_AXIS);
    c.setLayout(layout);
    c.add(wheelPanel); //add panel and animate canvas to the applet
    c.add(btPanel);
    wheel = getImage(getDocumentBase(),"rotary2.gif");
    getParameters();
    for(int k = 0; k <TOTAL_SECTORS; k++)
    polySectors[k] = new Polygon();
    for(int n= 0; n<4; n++)
    polySectors[k].addPoint(coordsX[k][n],coordsY[k][n]);
    btPlay.addActionListener(this);
    btStop.addActionListener(this);
    wheelPanel.addMouseListener(this);
    startAnimation();
    public void mouseClicked(MouseEvent e)
    if (rotating == false) //user can only hightlight a sector when wheel is not rotating
    for(int h= 0; h<TOTAL_SECTORS; h++)
    if(polySectors[h].contains(e.getX(),e.getY()))
    currentSector = h;
    wheelPanel.repaint();
    email();
    public void mouseExited(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseReleased(MouseEvent e){}
    public void mousePressed(MouseEvent e){}
    public void email()
    try
    URL rotaryMail = new URL("mailto:[email protected]");
    getAppletContext().showDocument(rotaryMail);
    catch(MalformedURLException mue)
    System.out.println("bad url!");
    public void getParameters()
    StringTokenizer stSector;
    String parCoords;
    for(int i = 0; i <TOTAL_SECTORS; i++)
    {               //put member names in applet parameter list into an array
    members[i] = getParameter("member"+i);
    //separate coordinate string and store coordinates in 2 arrays
    parCoords=getParameter("sector"+i);
    stSector = new StringTokenizer(parCoords, ",");
    for(int j = 0; j<4; j++)
    coordsX[i][j] = Integer.parseInt(stSector.nextToken());
    coordsY[i][j] = Integer.parseInt(stSector.nextToken());
    public void actionPerformed(ActionEvent e)
    wheelPanel.repaint(); //repaint when timer event occurs
    if (e.getActionCommand()=="Stop")
    stopAnimation();
    else if(e.getActionCommand()=="Play")
    startAnimation();
    public void startAnimation()
    if(timer == null)
    timer = new Timer(delay,this);
    timer.start();
    else if(!timer.isRunning())
    timer.restart();
    Thanks so much for your help!

  • Accessing Enclosing Class Members From Inner Class Subclass

    I have the following scenario that I cannot get to work. Notice the comments in B.doWork() for the problem code. In B.doWork(), how do I access m_strA?
    * A.java
    * Created on July 5, 2002, 2:20 PM
    package Projects.InnerTrouble.Files;
    public class A {
         public abstract class InnerA {
              public abstract void doWork ();
         public String m_strA;
         /** Creates new A */
         public A ()
                   new InnerA() {
                             public void doWork ()
                                       System.out.println("A$InnerA$1's doWork() called!");
                                       m_strA = "Annonymous subclass of InnerA's doWork did this";
                        }.doWork();
         * @param args the command line arguments
         public static void main (String args[])
                   A oTemp = new A();
                   System.out.println(oTemp.m_strA);
                   B.getB(oTemp).doWork();
                   System.out.println(oTemp.m_strA);
    class B extends A.InnerA {
         public B (A a)
                   a.super();
         public void doWork ()
                   System.out.println("B's doWork() called!");
                   // How do I access m_strA within B's doWork() method?  The following is what I would expect to be the answer, but it does not compile
                   // A.this.m_strA = "B's doWork did this";
         private static A.InnerA sm_oInnerA;
         public static A.InnerA getB (A a)
                   if (sm_oInnerA == null)
                        sm_oInnerA = new B(a);
                   return (sm_oInnerA);

    The whole point is that B is not an inner class of A
    so it does not have access to A's member variables.
    Eventhough B extends an inner class of A, that does
    not make B an inner class of A. That is in the JLS,
    but not so elegantly as I have put it, hehe.
    If B were an innerclass of InnerA, then it would
    qualify to access A's member variables.OK, I think that you are finally getting through to my thick skull on this one. Let me restate and get your check-off on my understanding of the situation.
    The only classes with access to A's this reference are A and inner classes of A that are found within the definition of A. So, despite the fact that A and B are in the same package (and B should have access to A's non-private members because B and A are in the same package), and despite the fact that we would normally state that B "is a" InnerA (which is an inner class of A and would have access to a reference to the A.this reference), B is not allowed access to A.this (because B "is not really a" InnerA in the same way that the anonymous implementation of InnerA "is a" InnerA). However, nothing would prevent me from giving B access to a reference of the enclosing A as long as it was done via a method of InnerA, and as long as the implementation of that method is contained in A's implementation.
    Does this "access" rule realy make sense? Are you aware of the justification for this rule? Or is the justification stated in the JLS? I would think that the compiler ought to be able to figure this kind of thing out and allow it. It seems to me the fact that I defined B in the way that I did, and the fact that B "is a" InnerA, implies that I desired a fairly tight relationship to A. In fact, I desired the exact relationship that exists for the anonymous implementation of InnerA.
    The following is a modified version of my original example that runs as I originally wanted it to, but works around the access rules discussed on this forum thread:
    * A.java
    * Created on July 5, 2002, 2:20 PM
    package Projects.InnerTrouble.Files;
    public class A {
         public abstract class InnerA {
              public abstract void doWork ();
              /** added to allow implementors of InnerA that are not enclosed in A's class definition to have access to the enclosing class */
              public A myEnclosingInstance ()
                        return (A.this);
         public String m_strA;
         /** Creates new A */
         public A ()
                   new InnerA() {
                             public void doWork ()
                                       System.out.println("A$InnerA$1's doWork() called!");
                                       m_strA = "Annonymous subclass of InnerA's doWork did this";
                        }.doWork();
         * @param args the command line arguments
         public static void main (String args[])
                   A oTemp = new A();
                   System.out.println(oTemp.m_strA);
                   B.getB(oTemp).doWork();
                   System.out.println(oTemp.m_strA);
    class B extends A.InnerA {
         public B (A a)
                   a.super();
         public void doWork ()
                   System.out.println("B's doWork() called!");
                   // The following is what I would expect to be the answer, but it does not compile
                   // A.this.m_strA = "B's doWork did this";
                   // added myEnclosingInstance() to get functionality desired above
                   myEnclosingInstance().m_strA = "B's doWork did this";
         private static A.InnerA sm_oInnerA;
         public static A.InnerA getB (A a)
                   if (sm_oInnerA == null)
                        sm_oInnerA = new B(a);
                   return (sm_oInnerA);
    }

  • Assign value in a inner class

    Suppose, we have the following two classes.
    public class test{
    final trythis t;
    t = null;
    doMethod(t); // because of this, t has to be assigned a null value
    (new Thread(){public void run(){
        t = new trythis();  // t is assigned twice
      }}).start();
    class trythis{
    trythis(){
    t seems to have to be defined as final, but final instance cannot be set in the inner class.
    Does anyone know how to solve this problem?
    Thanks

    As the local variable has a lifetime of the executing method's
    duration, you must ensure the innerclass (which has a longer lifetime)
    has access to it by declaring it final.This is not quite exact. All this is due to the way inner classes are implemented. An inner class maintains the contents of the outer local variables used in two ways:
    - If it is primitive, use the value verbatim (so the class has no relationship to the outer variable, it just uses the same number, so the local var needs to be final or else there could be surprises for a programmer who would think that changing the local var would also change the value used in the inner class)
    - If it is a reference, copy it as a class member, and use that one wherever needed. For similar reasons as above, the two references have to be in sync, so the local var has to be final (the inner var can't change anyway)
    This apply only to local variables because class members are accessible through a secret reference of the enclosing object passed in the constructor of the inner class. Static members are anyway accessible.
    <teacher's mode off/>
    <sorry for that, but someone might find the explanation useful :-)/>
    By the way, the OP can get the value "t" out of the inner class by providing a special Thread subclass, ie
    class MyThread extends Thread {
      public void run() {
        t = something;
      trythis t;
    MyThread thread = new MyThread();
    thread.start();
    thread.join();
    thread.t; //This is accessibleI'm not sure if this would be preferable to the array approach (which is ), but it is useful to know your alternatives

  • Application & JApplet - Inner Classes

    Hi,
    I am having problems understanding the purpose of Inner Classes.
    1. Is purpose of inner class in an Application to take care of what init method
    takes care of in a JApplet. I believe init method in JApplet brings up the browser and
    xecutes statements in init()?
    2. Is it possible to write the enclosed Application without using an Inner Class?
    If so, can someone please show me how?
    3. Is it possible to write the enclosed JApplet using an inner Class?
    If so, can someone please show me how?
    Maybe if I see how an Application and JApplet are written with and without inner classes, this may help me understand.
    Thank you.
    //APPLICATION USING AN INNER CLASS
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    //outerclass
    public class InnerTest extends JFrame
    private JTextField numField, sumField;
    private int sum = 0;
    public InnerTest()
    super("Inner Test");
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    ActionEventHandler handler = new ActionEventHandler();
    numField = new JTextField(10);
    sumField = new JTextField(10);
    numField.addActionListener(handler);
    c.add(numField);
    c.add(sumField);
    public static void main(String args[])
    InnerTest win = new InnerTest();
    win.setSize(400, 140);
    win.show();
    //Innerclass
    private class ActionEventHandler implements ActionListener
    public void actionPerformed(ActionEvent e)
    sum += Integer.parseInt(numField.getText()); // access to sum and numField
    numField.setText("");
    sumField.setText(Integer.toString(sum));
    JAPPLET
    Below is modification of above code to a JApplet
    without using inner class. I have CAPITALIZED MODIFICATIONS.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class InnerTest extends JAPPLET
    private JTextField numField, sumField;
    private int sum = 0;
    public VOID INIT()
    super("Inner Test");
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    ActionEventHandler handler = new ActionEventHandler();
    numField = new JTextField(10);
    sumField = new JTextField(10);
    numField.addActionListener(THIS);
    c.add(numField);
    c.add(sumField);
    public void actionPerformed(ActionEvent e)
    sum += Integer.parseInt(numField.getText()); // access to sum and numField
    numField.setText("");
    sumField.setText(Integer.toString(sum));

    1. Is purpose of inner class in an Application to
    take care of what init method
    takes care of in a JApplet. I believe init method in
    JApplet brings up the browser and
    xecutes statements in init()?No. The init() method of an applet is similar to the constructor for an application. It is used to initialize data for the applet, the same data you will initialize in the constructor of the application.
    >
    2. Is it possible to write the enclosed Application
    without using an Inner Class?Yes it is possible. The power of an inner class is that is has access even to private member variables of the enclosing class. In your case the event handler has access to the private variables: numField and sumField. If you do not use an inner class you have to pass a reference to your frame in the event handler's constructor and access the variables through that reference. But in this case you do not have access to private variables. So you must provide methods to access those variables or you must change theri visibility.
    ActionEventHandler handler = new ActionEventHandler(this);Provide accessor methods in InnerTest class:
    public String getTextString(){
         return numField.getText();
    public void setTextString(String text){
         numField.setText(text);
    }As for the applet it works just as your application in this case, you can use inner classes or not but with the same restrictions.
    I hope you can understand what I tried to explain.

  • Inner class access to outer class variables

    class X extends JTextField {
    int variable_a;
    public X() {
    setDocument(
    new PlainDocument() {
    //here i need access to variable_a
    i don't want to make variable_a a static member though, so does anyone know how to do it?

    Generally, you can reference your variable_a just as you would any other variable except if your inner class also defines a variable_a. However, to produce a reference to the enclosing outer class object you write "OuterClassName.this". So, to get to your variable I think you would write "X.this.variable_a". I hope this helps.

  • Local inner class scope

    Hello all,
    I am working out of "Thinking in Java" and ran across something I simply don't get. A method is called and passed an argument. This method defines an inner class and returns reference to it. Later a method in the inner class is invoked, but it still has access to the argument passed to the method that created the inner class and completed.
    Here is the code (shortened from the book):
    interface Counter {
         int next();
    } // close interface Counter
    public class LocalInnerClass {
         private int count = 0;
         Counter getCounter( final String name ) {
              class LocalCounter implements Counter {
                   public int next() {
                        System.out.print( name );
                        return count++;
                   } // close next()
              } // close inner class
              return new LocalCounter();
         } // close getCounter()
         public static void main( String[] args ) {
              LocalInnerClass lic = new LocalInnerClass();
              Counter c1 = lic.getCounter( "Local inner " );
              for( int i = 0; i < 5; i++ ) {
                   System.out.println( c1.next() );
              } // close for
         } // close main()
    } // close classAnd here is what is produced from running this:
    Local inner 0
    Local inner 1
    Local inner 2
    Local inner 3
    Local inner 4The string "Local inner" is passed to the method getCouter as a final String. getCounter creates the class and exits. Later a method in getCounter uses that final String "next". This is where I am lost - getCounter is done and gone, so how the heck is name accessible to the inner class?!?!
    Just when I thought I was getting the hang of this ;)

    So trying to redeem myself...
    You can use "javap -c" to see what a compiler is really doing.
    So using javap (version 1.4.2_04) on the inner class gives the following....
    class LocalInnerClass$1LocalCounter extends java.lang.Object implements Counter{
    LocalInnerClass$1LocalCounter(LocalInnerClass,java.lang.String);
      Code:
       0:   aload_0
       1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
       4:   aload_0
       5:   aload_1
       6:   putfield        #2; //Field this$0:LLocalInnerClass;
       9:   aload_0
       10:  aload_2
       11:  putfield        #3; //Field val$name:Ljava/lang/String;
       14:  return
    public int next();
      Code:
       0:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
       3:   aload_0
       4:   getfield        #3; //Field val$name:Ljava/lang/String;
       7:   invokevirtual   #5; //Method java/io/PrintStream.print:(Ljava/lang/String;)V
       10:  aload_0
       11:  getfield        #2; //Field this$0:LLocalInnerClass;
       14:  invokestatic    #6; //Method LocalInnerClass.access$008:(LLocalInnerClass;)I
       17:  ireturn
    The second method in the above is the next() method.
    The next() method uses the "getfield" bytecode to retrieve a member variable of the class which is named "val$name".
    The first method in the above is a constructor which takes a string as the only parameter. That string is saved in the member variable of the class called "val$name".
    It is preserving a reference, so if a StringBuffer was used rather than a String then one could alter the value in the for loop of the original code and see the change.

  • Problem with constructor of inner class.

    Hi everybody!
    I have an applet which loads images from a database.
    i want to draw the images in a textarea, so i wrote an inner class, which extends textarea and overrides the paint method.
    but everytime i try to disply the applet in the browser this happens:
    java.lang.NoClassDefFoundError: WohnungSuchenApplet$Malfl�che
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:1590)
    at java.lang.Class.getConstructor0(Class.java:1762)
    at java.lang.Class.newInstance0(Class.java:276)
    at java.lang.Class.newInstance(Class.java:259)
    at sun.applet.AppletPanel.createApplet(AppletPanel.java:567)
    at sun.plugin.AppletViewer.createApplet(AppletViewer.java:1778)
    at sun.applet.AppletPanel.runLoader(AppletPanel.java:496)
    at sun.applet.AppletPanel.run(AppletPanel.java:293)
    at java.lang.Thread.run(Thread.java:536)
    so my class has no own constructor, it just has the paint method overwritten.
    my class looks like this:
    public class Malfl�che extends javax.swing.JTextArea{
    public void paint(Graphics g){
    Color grey=new Color(220,220,220);
    g.drawImage(img,10,10,null);
    how should a constructor for this class look like?
    sorry i am quite new to this, so i really dont have a clue!
    my class does not have any attributes or requires any so it doesnt need a constructor, doesnt it?
    thanks a lot
    tim

    First off, unlike regular classes, inner classes can be declared public, private, protected, and default.
    Secondly, why are you using the JTextArea to display an image, why not use a JLabel, which takes an Image object as its constructor.
    Thirdly, when you drew your image you did not give it a width and height
    g.drawImage(img, 0,0, img.getWidth(null), img.getHeight(null), null);
    otherwise it will make your image 1 X 1 pixels. not big enough to see.

  • Threaded inner classes & heap memory exhaustion

    (_) how can i maximize my threading without running out of
    heap memory?
    push it to the limit, but throttle back before an
    java.lang.OutOfMemoryError.
    (_) within 1 threaded class ThreadClass, i have two threaded inner classes. for each instance of ThreadClass i only
    start one instance of each inner class.
    and, i start hundreds of ThreadClass, but not until the previously running ThreadClass object exits, so only one should be running at any given time.
    so, what about threaded inner classes?
    are they good? bad? cause "OutOfMemoryErrors"?
    are those inner threads not dying?
    what are common causes of:
    java.lang.OutOfMemoryError: java heap space?
    my program runs for about 5-minutes, then
    bails with the memory error.
    how can i drill down and see what
    is eating-up all my memory?
    thanks.

    A Thread class is not the same as a thread of
    execution. Those inner class based threads of
    execution are not dying.maybe. but this is the way i test a thread's life:
    public void run() {
    System.out.println("thread start");
    System.out.println("thread dies and release memory");
    }for each inner thread, and the outer thread, this approach for
    testing thread life reveals that they die.
    Why don't you use a thread pool?ok. i will think about how to do this.
    >
    If not, you need to ensure those inner threads have
    exited and completed.what is a 100% sure check to guarantee a thread exits other than
    the one i use above?
    note:
    the outer thread is running on a remote host, and the inner threads
    are running locally. here are the details:
    public class BB implements Runnable, FinInterface {
      public void run() {
        // do some work on the remote machine
      private void startResultsHandler(OisXoos oisX) {
         ResultHandler rh = new ResultHandler(oisX);
         rh.start();
      public void startDataProxy(OisXoos oisX, String query) {
         DataProxy dp = new DataProxy(oisX, query);
         dp.start();
            public class ResultsHandler extends Thread {
               // runs locally; waits for results from servers
               public void run() {
                   ObjectInputStream ois = new ObjectInputStream(oisX.input);
                    Set result = (Set) ois.readObject();
            }  // ____ class :: _ ResultsHandler _ :: class ____
           public class DataProxy extends Thread {
               // runs locally; performs db queries on behalf of servers
               public void run() {
                   ObjectOutputStream oos = new ObjectOutputStream(oisX.output);
                    while(moreData) {
                        .... // sql queries
                        oos.writeObject(data);
                 StartResultsHandler(oisX);
            } // _____ class  :: _ DataProxy _ :: class _____
    }now, the BB class is not started locally.
    the inner threads are started locally to both service data requests
    by the BB thread as well as wait for its results.
    (_) so, maybe the inner threads cannot exit (but they sure look
    like they exit) until their parent BB thread exits.
    (_) yet, those inner threads have no knowledge that the BB
    thread is running.
    externalizing those inner thread classes will put 2-weeks of work
    in the dust bin. i want to keep them internal.
    thanks.
    here this piece of code that controls everything:
    while(moreData) {
      FinObjects finObj = new BB();
      String symb = (String) data_ois.readObject();
      OisXoos oisX = RSAdmin.getServer();
      oisX.xoos.writeObject(finObj);
      finObj.startDataProxy(finObj, oisX, symb);
    }

Maybe you are looking for