Howto instatiate array of inner classes

Hi, I couldn't find the syntax for doing this.
I just want to instantiate an array of inner classes (non-static). It says '(' expected.
Here is a small sample:
public class test_inner {
public class inner1 {
public inner1 inner1_inst;
public class inner2 {
public inner2[] inner2_ar;
public static void foo() {
test_inner inst = new test_inner(); // OK
inst.inner1_inst = inst.new inner1(); // OK, single inst
inst.innter2_ar = inst.new inner2[10]; // fails to compile
// also tried [10]() even ()[10] ...
Using java 1.6 Win32.
As always grateful for any help.

The following compiles OK:public class test_inner {
    public class inner1 {}
    public inner1 inner1_inst;
    public class inner2 {}
    public inner2[] inner2_ar;
    public static void foo() {
        test_inner inst = new test_inner();
        inst.inner1_inst = inst.new inner1();
        inst.inner2_ar = new test_inner.inner2[10];
        // inst.inner2_ar = inst.new inner2[10]; // fails to compile
        // also tried [10]() even ()[10] ...
}When creating inst.inner2_ar you don't use a qualified class instance creation expression (JLS 15.9) because what is being created is not an inner member class: it's an array. So the syntax for creating it is that of JLS 15.10.

Similar Messages

  • How to declared an array of inner class ?

    can we declare array of inner class ?

    for example:
    Country.City.Airport.Flight[] fly = Country.City.Airport.Flight[VALUE];
    fly[0] = ( ( (new Country()).new City()).new Airport() ).new Flight();
    System.out.println(fly[0].toString());
    Class Country {
    Class City{
    Class Airport{
    Class Flight{
    }

  • Pass an array of argument defined anonymous inner class

    Can someone plz tell me what is wrong with this code?How can I correct it?
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[5]{
                   public void disp(){
                        System.out.println("Array of inner classes disp");
    }     

    This is what I wanted to do:
    interface NotImplemented{
         public void disp();
    public class Anonymous{
         public void disp(NotImplemented[] ni){
              System.out.println(ni.length);
              ni[0].disp();
              ni[1].disp();
         public static void main(String args[]){
              Anonymous a=new Anonymous();
              a.disp(new NotImplemented[]{
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside first implementor of NotImplemented interface");
                        new NotImplemented(){
                             public void disp(){
                                  System.out.println("Inside second implementor of NotImplemented interface");
    Thanks for all your help...

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

  • Menu's and Inner classes

    I am currently writing my own Chess game in Java and not very well. I want to add a 'New' section to a drop down list which sets the board back to the starting positon. But to do this I need to call a method of a class created in the outer class in the Inner class to set the array that the board is based upon to the default. Is this possible.
    If anyone could help I would be very greatful.
    Kindest Regards Deniz Tanay

    "I need to call a method of a class created in the outer class in the Inner class..."
    This doesn't make sense to me. A "class created in the outer class"? Usually the compiler creates classes. What do you mean by this phrase?
    If you wanted to call a method of the outer class, that would be easier to explain.

  • Inner classes should appear in jar?

    At first thanks for answering my question: I did resolve the problem of excluding files, so the .java and .html are not present anymore�.. but the problem stays: I do see the applet in the applet viewer but not on the safari (mac Version 3.0.4) browser. The tag, I think is ok:
    <applet code="Slides.class" width="500" height="500" archive="slides.jar"></applet>
    A second question related to this problem might be, that the two inner class files that show up in the build/class file are not present in the jar. The application consists of just one single class (I already moved some initialization stuff from the constructor to the init). The class is called Slides.class and the compiler generates the Slides$1, Slides$xxx and Slides$yyyy. Should they all be included in the jar I only so the main class.
    Thanks a lot
    willemjav
    The (still dirty) code is here (you need a folder with images files called xxxx#img01 etc.) and a first image called firstpic.jpg
    * Slides
    * Created on February 3, 2008, 10:25 PM
    * The application does an applet slide show
    * of a list of images files set in the folder
    * Imagestore each 7 seconds changes the picture
    * see DURATION
    * still to do an image list check on file extentions
    * and a fade in/ out
    * @author wdragstra
    import java.awt.*;
    import java.awt.Image;
    import java.awt.event.*;
    import java.text.DecimalFormat;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.net.URL;
    import java.io.*;
    import java.awt.image.BufferedImage;
    public class Slides2 extends JPanel implements ActionListener {
    private int count, maxcount, x, y, duration,
    textposx, textposy, imgwidth, imgheight;
    static int framew, frameh;
    private boolean intro;
    private static final int LOAD = 7000, PAUSE=4000; // animation duration
    private static final String FILE_NAME="Imagestore"; // the image file name in work directory
    private File directory; // File object referring to the directory.
    private String[] picfilenames; // Array of file names in the directory.
    private JOptionPane infoPane;
    private JPanel picttextPanel;
    private JLabel textLabel;
    private Timer load, timer, pause;
    private Image firstpic;
    private BufferedImage OSC;
    public Slides2() { // construtor
    framew = 350; // frame size to be set
    frameh = 390;
    textposx = 130; // text position to be set
    textposy = 20;
    duration = 9000; // image duration to be set
    count=0; // image and textstring counters
    maxcount = 0;
    load = new Timer(LOAD, this); // the three animation timers
    readImageFilelist(FILE_NAME); // get the content of the image folder
    firstpic = downloadImage("firstpic.jpg");
    orderImages();
    timer = new Timer(duration, this);
    infoPane = new JOptionPane(); // containing the 1) firstpic.jpg the
    picttextPanel = new JPanel(); // first picture or only picture
    textLabel = new JLabel(" INFO ", JLabel.CENTER); // 2) the parameter file called
    this.setLayout(null); // imageanimater.txt 3) the imgefiles
    textLabel.setBounds(textposy,textposx, 300 , 50); // with name xxxxx#img01 - 99
    add(textLabel);
    intro = true;
    load.start();
    public void actionPerformed(ActionEvent evt) { // timer listner
    if (evt.getSource() == load) { // first timer only ones for first picture
    // second timer for image duration
    load.stop();
    timer.start();
    intro=false;
    repaint();
    if (evt.getSource() == timer) {
    if (count == maxcount)
    count = 0;
    repaint();
    count++;
    void readImageFilelist(String dirname) { // gets the list of images
    directory = new File(dirname); // of folder imagestore
    if (directory.isDirectory() == false) { // in work directory
    if (directory.exists() == false)
    JOptionPane.showMessageDialog(infoPane,
    " there is no directory called " + directory);
    else
    JOptionPane.showMessageDialog(infoPane, directory +
    " is not a directory. ");
    else {
    picfilenames = directory.list(); // stores the list of file names
    for (int i = 0; i < picfilenames.length; i++) {
    if (imageNamecheck(picfilenames)) { // check correct file extension #img
    picfilenamesmaxcount = picfilenames; // eliminate the incorrect ones
    maxcount++;
    if (maxcount == 0)
    JOptionPane.showMessageDialog(infoPane,
    "no valid files present ");
    private boolean imageNamecheck(String st) {
    int pos = st.indexOf("#img");
    if (pos == -1)
    return false;
    else return true;
    private int imagePos(String st) {
    int posnmb=0; // convert string-number into int
    int pos = st.indexOf("#img"); // when no image present returns -1
    if (pos==-1) {
    JOptionPane.showMessageDialog(infoPane,
    "The file has�t the correct format #img01-#img99 ");
    return 0;
    else
    return pos+4;
    private void orderImages() { // sort de file list of images 00-99
    int lastarray = maxcount-1;
    int trynmb=0, maxnmb=0, index=0, pos=0;
    String tempfl="";
    while(lastarray != 0) {
    index = 0;
    pos = imagePos(picfilenames[0]);
    try { maxnmb = Integer.parseInt(picfilenames[0].substring(pos, pos+2));
    catch ( NumberFormatException e ) {
    JOptionPane.showMessageDialog(infoPane,
    "File format: #img01-#img99 " + e);
    for (int i = 1; i <= lastarray; i++) {
    pos = imagePos(picfilenames);
    try { trynmb = Integer.parseInt(picfilenames.substring(pos, pos+2));
    catch ( NumberFormatException e ) {
    JOptionPane.showMessageDialog(infoPane,
    "File format: #img01-#img99 " + e);
    if (trynmb>maxnmb) {
    maxnmb = trynmb;
    index=i;
    tempfl = picfilenameslastarray;
    picfilenameslastarray = picfilenamesindex;
    picfilenamesindex = tempfl;
    lastarray--;
    // for (int i = 0; i < maxcount; i++) {
    //JOptionPane.showMessageDialog(infoPane,
    // "last array " + i + " filename " + picfilenames);
    private Image scaleImage(BufferedImage bimg) { // scale buffered image into image fill
    try {
    imgwidth = bimg.getWidth(this);
    catch (Exception e) {
    JOptionPane.showMessageDialog(infoPane, "can not get image width " + e);
    try {
    imgheight = bimg.getHeight(this);
    catch (Exception e) {
    JOptionPane.showMessageDialog(infoPane, "can not get image height " + e);
    double scalerate = calcScale(imgwidth, imgheight); // calls the actual scaling method
    imgwidth = (int)(imgwidth * scalerate);
    imgheight = (int)(imgheight * scalerate);
    x = (int)(framew - imgwidth)/2;
    y = (int)(frameh - imgheight)/2;
    DecimalFormat myFormatter = new DecimalFormat("######.##");
    String xx = myFormatter.format(scalerate);
    String yy = myFormatter.format(scalerate);
    //JOptionPane.showMessageDialog(infoPane,
    // "image size " + imgwidth + " / " + imgheight + " new size " + newidth + " / " + newheight + " scalerate " + xx
    // + " insets " + insetw + " / " + inseth );
    try {
    Image img = bimg.getScaledInstance(imgwidth, imgheight, bimg.SCALE_FAST); // the actual scaling
    return img;
    catch (IllegalArgumentException e) {
    JOptionPane.showMessageDialog(infoPane, " can not scale the image " + bimg + " " + e);
    return null;
    private double calcScale(int imgwidth, int imgheight) {
    double sc=0, x=0;
    if ((double)framew-imgwidth < frameh-imgheight) { // gets the smallest side of the picture
    sc = (double)framew/imgwidth; // to scale to frame size (sc)
    else {
    sc = (double)frameh/imgheight;
    return sc;
    private Image downloadImage(String filename) { //downloads image and call the scaling
    BufferedImage bufimg=null;
    Image img=null;
    ClassLoader cl = Slides2.class.getClassLoader();
    URL imageURL = cl.getResource(filename);
    try {
    bufimg = ImageIO.read(imageURL);
    img=scaleImage(bufimg);
    catch (Exception e){
    JOptionPane.showMessageDialog(infoPane, " can not download " + filename + " " + e);
    return img;
    private void displayText(int cnt) {
    textLabel.setFont(new Font("Serif", Font.BOLD, 18));
    textLabel.setForeground(Color.RED);
    textLabel.setText("xcount maxcount " + count + " / " + maxcount);
    public void paintComponent(Graphics g) { // the timer calls the component
    // to draw the pictures
    if (intro) { // the first pic and its display time
    g.drawImage(firstpic,0, 0, imgwidth, imgheight, this);
    else {
    //g.drawImage(img, dest_x1, dest_y1, dest_x2, dest_y2,
    // source_x1, source_y1, source_x2, source_y2, imageObserver); x=width y=height
    g.setColor(Color.WHITE);
    g.fillRect(0, 0, framew+10, frameh+10);
    g.drawImage(downloadImage(picfilenamescount),x, y, imgwidth, imgheight,this);
    //g.drawImage(firstpic,0, 0, imgwidth, imgheight, this);
    displayText(7);
    }

    If the application is expecting to find an inner class in the jar - then yes, it must be there.
    Put it in there and see what happens - it is probably needed there.

  • 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

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

  • 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

  • Private inner class with private constructor

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

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

  • Instantiation an inner class using reflection

    I want to instantiate an inner class using the Class.newInstance() method called within the Outer class constructor:
    public Outer
    public Outer()
    Inner.class.newInstance();
    private Class Inner { }
    When I try it, however, I get an InstantiationException.
    Is there some way to do this?
    Thanks for the help.
    Scott

    Here is a consolidation of what everyone posted and it does appear to work. In one of your post you used the getDeclaredConstructors() method and said it was less than ideal; I am not sure what you meant but I suspect it was the hard coded array reference. Anyhow I used the getDeclaredConstructor() method which appears to get non-public constructors also and is basically the same as using the getConstructor() method.
    import java.lang.reflect.*;
    public class Test35 {
        static public void main(String[] args) {
            Test35 t35 = new Test35();
            t35.testIt();
        private class Inner {
            public String toString() {
                return "Hear I am";
        public void testIt() {
            try {
                Constructor con = Inner.class.getDeclaredConstructor(new Class[] {Test35.class});
                Inner in = (Inner)con.newInstance(new Object[] {this});
                System.out.println(in);
            } catch (Exception e) {
                e.printStackTrace();

  • From sunś Inner Class Exampel

    Hi Have a questions about the exampel
    [http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html]
    public void printEven() {
            //print out values of even indices of the array
            InnerEvenIterator iterator = this.new InnerEvenIterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.getNext() + " ");
        }The keword "this" is still a problem for me. I start to belive im stupid or something.
    Can you please explain what it does here? why not just write
    InnerEvenIterator iterator = new InnerEvenIterator();Regards / Magnus

    In the context of the example, this. is optional, but the authors were trying to emphasize that it's not simply a matter of creating an instance of any old class, so they explicitly used the this reference. The class reference is not always optional. If the printEven() method were defined as static, there would already have to be an instance of DataStructure such as ds created before the inner class could be instantiated:DataStructure ds = new DataStructure();
    InnerEvenIterator iterator = ds.new InnerEvenIterator();

  • Mysterious anonymous inner class in switch block

    public class MysteryFile {
      public enum Elements {
        WIND, EARTH, FIRE, WATER
      Elements el;
      public MysteryFile(Elements el) {
        this.el = el;
      public void whatIsItLike() {
        switch (el) {
          case WIND: System.out.println("A bit chilly sometimes"); break;
          case EARTH: System.out.println("Gets hands dirty."); break;
          case FIRE: System.out.println("Hot! skin melt"); break;
          case WATER: System.out.println("Cool! clean hands"); break;
          default: System.out.println("Don't know"); break;
      public static void main(String[] args) {
        MysteryFile anElement = new MysteryFile(Elements.FIRE);
        anElement.whatIsItLike();
    }When compiled in Netbeans or in the command line, generates an unexpected MysteryFile$1.class file. If the entire switch block is commented out and recompiled, it does not get generated. Where does this anonymous inner class come from?

    The MysteryFile$1 class looks something like this (javac 1.6.0_02):
    class MysteryFile$1 {
      static final int[] $SwitchMap$MysteryFile$Elements;
      static {
          // the line number (debug info) of this static initializer
          // is "switch (el)" line in MysteryFile.java
          $SwitchMap$MysteryFile$Elements =
                  new int[MysteryFile$Elements.values().length ];
          try {
              $SwitchMap$MysteryFile$Elements[
                      MysteryFile$Elements.WIND.ordinal() ] = 1;
          } catch (NoSuchFieldError e) {
              // fix stack?
          // repeat with EARTH(2), FIRE(3) and WATER(4)
    }... and the actual switch statement in 'MysteryFile' looks like so:
      //switch (el) {
      switch(MysteryFile$1.$SwitchMap$MysteryFile$Elements[
              this.el.ordinal() ])
      case 1:  // WIND
          break;
      case 2:  // EARTH
          break;
      case 3:  // FIRE
          break;
      case 4:  // WATER
          break;
      default:  // ...
      }I suppose this is necessary because the compiler can't guarantee that the runtime enum-constant-to-ordinal mapping will be identical to that at compile time (the API docs say it depends on the declaration order in the source code, which I think may change without breaking binary compatibility).
    PS MysteryFile$Elements.values() is a synthetic method that returns all enumeration constants in a MysteryFile$Elements array. Found this old related thread: [http://forum.java.sun.com/thread.jspa?threadID=617315]

  • Question about inner class - help please

    hi all
    i have a question about the inner class. i need to create some kind of object inside a process class. the reason for the creation of object is because i need to get some values from database and store them in an array:
    name, value, indexNum, flag
    i need to create an array of objects to hold those values and do some process in the process class. the object is only for the process class that contains it. i am not really certain how to create this inner class. i tried it with the following:
    public class process{
    class MyObject{}
    List l = new ArrayList();
    l.add(new MyObject(....));
    or should i create the object as static? what is the benifit of creating this way or static way? thanks for you help.

    for this case, i do need to create a new instance of
    this MyObject each time the process is running with a
    new message - xml. but i will be dealing with the case
    where i will need a static object to hold some
    property values for all the instances. so i suppose i
    will be using static inner class for that case.The two situations are not the same. You know the difference between instance variables and static variables, of course (although you make the usual sloppy error and call them static objects). But the meaning of "static" in the definition of an inner class is this: if you don't declare an inner class static, then an instance of that inner class must belong to an instance of its containing class. If you do declare the inner class static, then an instance of the inner class can exist on its own without any corresponding instance of the containing class. Obviously this has nothing to do with the meaning of "static" with respect to variables.

  • Problem with Outer and Inner Classes....or better way?

    Right now I'm trying to create an Inner class.
    My .java file compiles ok, and I create my jar file too.
    But when I try to instantiate the Inner class, it fails:
    java.lang.NoClassDefFoundError: com/myco/vlXML/vlXML$vlDocument.
    Here's the class code:
    public class vlXML{
        private ArrayList myDocList=new ArrayList(); //holds documents
        public vlXML(){
        private class vlDocument{
            public vlDocument(){
            //stuff goes here
        public vlDocument vlDOC(){
            return new vlDocument();
        public void addDocument(){
            vlXML xxx=new vlXML();
            vlDocument myDoc=xxx.vlDOC();
            myDocList.add(myDoc);
        public int getNumDocs(){
            return myDocList.size();
    }Then, from a jsp page, I call:
    vlXML junk1=new vlXML();
    junk1.addDocument();...and get the error...
    Can someone help me figure out why it's failing?
    Thanks....

    You nailed it - thanks....(duh!)
    While I have your attention, if you don't mind, I have another question.
    I'm creating a Class (outer) that allows my users to write a specific XML file (according to my own schema).
    Within the XML file, they can have multiple instances of certain tags, like "Document". "Document"s can have multiple fields.
    Since I don't know how many "Documents" they may want, I was planning on using an Inner Class of "Document", and then simply letting them "add" as many as necessary (thus the original code posted here).
    Does that seem like an efficient (logical/reasonable) methodology,
    or is there there something better?
    Thanks Again...

Maybe you are looking for