Private inner classes, should this compile:

class Outer
&nbsp&nbsp&nbsp&nbspclass InnerA;
&nbsp&nbsp&nbsp&nbspclass InnerB;
&nbsp&nbsp&nbsp&nbspclass InnerA
&nbsp&nbsp&nbsp&nbsp{
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspInnerB* m_inner;
&nbsp&nbsp&nbsp&nbsp};
&nbsp&nbsp&nbsp&nbspclass InnerB
&nbsp&nbsp&nbsp&nbsp{
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspInnerA* m_inner;
&nbsp&nbsp&nbsp&nbsp};
The Sun Studio 8 C++ compiler says that InnerB is not accessible from InnerA and vica-versa.
However, both classes are members of the outer class and I would think that just like member functions, they should have access to all the declarations (prviate or not) in the outer class.
Is the compiler correct to complain about this?
Kind Regards,
Dave.

the current wording of the standard favours the Sun' s interpretation.
gcc have gone with assuming that core language defect report 45 will be accepted which would allow this.
see http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/cwg_defects.html#45 .
/lib

Similar Messages

  • Creating Private Inner Classes in Separate Files

    I sometimes find myself wanting to use private inner classes to do things, but then moving the classes to separate files and giving them package access just because I don't like having single large files.
    Is there a way to create private inner classes on a class but just save them in another file?
    Thanks,
    John

    For me, short file sizes usually make design structure
    more clear. This can make maintenance easier. It can
    also make browsing the code easier, even if you have a
    good editor or IDE. It is also less intimadating
    psychologically (for me, anyway) to work with a number
    of small files, each one with a distinct purpose, than
    it is to open up a monster, even if the monster does
    represent a coherent design unit in some sense. I
    think this psychological impact may be more important
    than most people give it credit for.The psychological impact is lessened if you use an IDE like VisualAge (where only one method at a time is generally displayed) or use the "Show Source Of Selected Element Only" option in Eclipse.
    It's one thing to say a method should be short and a class should have as few methods as possible. Those forces reduce complexity and ease maintenance. It's another to say a source file should be short. A source file is just a storage artifact; source code could be stored in a database without changing how the programmer interacts with it. The fact that the standard java compiler requires the implementation of nested classes to be stored inside the source file of their containing class is a minor inconvenience. Don't let it discourage you from using inner classes when they make sense. The design should not be driven by source file size considerations.
    >
    But you have added code only with the sole intent of
    making a source file smaller. If Java had amechanism
    for storing nested classes in other files youwouldn't
    do this. My point below was that you shouldn't let
    source file size override the decision to use anested
    class.Why shouldn't I let it? There are plenty of
    non-trivial benefits (the ones I gave above, for
    starters) to working with smaller files.Because all of those benefits can be gained from using a decent IDE. Eclipse is free. It can show only the current method and it can collapse nested classes.
    You say "If
    Java had a mechanism...." Well, I could answer: It
    does have such a mechanism, and that mechanism is
    packages.Packages are not a mechanism for creating private inner classes in separate files. Eclipse has a mechanism for making the fact that they reside in the same source file a non-issue.
    >>
    I am not being cavalier. I have no argument, onlyan
    opinion.Again, you are perfectly entitled to your opinion.
    But if it is truly an opinion, and nothing more, why
    bother telling me about it. You might as well post
    your favorite color. It is the reasons for your
    opinion that interest me, and you still have not
    really given any.I have had lengthy arguments about the issue of method and class size. Like I said before, I prefer very small classes and methods. I also think the number of nested classes should be as small as possible. But I have no problem with large files. Files are just one way to organize source code. The size of the things in the files matters, not the files themselves.

  • Private inner class

    I have a private inner class , the methods and constructor of this inner class should be private or default ?Please explain me what is the right method and constructor access modifier I should use to private inner classes .

    paulcw wrote:
    I believe that if you make the constructor private, nothing can instantiate it.Not true for an inner class.
    Re the original question: I'm not sure it really matters here, but I've not seen a canonical answer to this.

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

  • Compiler bug with generics and private inner classes

    There appears to be a bug in the sun java compiler. This problem was reported against eclipse and the developers their concluded that it must be a problem with javac.
    Idea also seems to compile the example below. I couldn't find a bug report in the sun bug database. Can somebody tell me if this is a bug in javac and if there is a bug report for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=185422
    public class Foo <T>{
    private T myT;
    public T getT() {
    return myT;
    public void setT(T aT) {
    myT = aT;
    public class Bar extends Foo<Bar.Baz> {
    public static void main(String[] args) {
    Bar myBar = new Bar();
    myBar.setT(new Baz());
    System.out.println(myBar.getT().toString());
    private static class Baz {
    @Override
    public String toString() {
    return "Baz";
    Eclipse compiles and runs the code even though the Baz inner class is private.
    javac reports:
    Bar.java:1: Bar.Baz has private access in Bar
    public class Bar extends Foo<Bar.Baz>
    ^
    1 error

    As I said in my original post its not just eclipse that thinks the code snippet is compilable. IntelliJ Idea also parses it without complaining. I haven't looked at the java language spec but intuitively I see no reason why the code should not compile. I don't think eclipse submitting bug reports to sun has anything to do with courage. I would guess they just couldn't be bothered.

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

  • Private inner classes

    I'm trying to complete a "turn the lightbulb on and off" program, but when I try to draw circle2 in the
    ButtonListener class I get an error message cannot find symbol. This is in reference to the Graphics
    variable "page" created in the paintComponent method below. Shouldn't the inner class, private or
    public inherit all data variables including objects from the parent class, in this case, the Bulb class? The code is below.
    By the way, this IS NOT a school assignment so any help would be appreciated. I'm just trying to learn
    this language.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Bulb extends JPanel
         private JButton push;
         private Circle circle, circle2;
         private final int DIAMETER = 100;
         private final int X = 10;
         private final int Y = 10;
         public Bulb()
              circle = new Circle(DIAMETER, Color.white, X,Y);
              circle2 = new Circle(DIAMETER, Color.yellow, X, Y); // to separate class
              push = new JButton("Turn on the Bulb");
              push.addActionListener(new ButtonListener());
              add(push);
              setPreferredSize(new Dimension(500, 500));
              setBackground(Color.black);
         public void paintComponent(Graphics page)
              super.paintComponent(page);
              circle.draw(page);
    private class ButtonListener implements ActionListener
              public void actionPerformed(ActionEvent event) //PROBLEM AREA. I GET ERROR MESSAGE STATING
    // "CANNOT FIND SYMBOL" IN REFERENCE TO VARIABLE "PAGE."
    // I THOUGHT THE INNER CLASS INHERITS ALL DATA FROM
    // PARENT CLASS SUCH AS "PAGE."
                   circle2.draw(page);
    }

    There are fields, which are associated with either a class or an object (and thus live in the heap in an object on the heap), and there are local variables, which are associated with methods and threads (i.e., a method invoked within a thread, and which thus live on the stack).
    They're not the same thing.
    You can't use a local variable in your paintComponent method in a different method.
    Anyway you're designing your class wrong. Think model-view-controller. You have the model: a bunch of state and possibly behavior that represents the thing being seen, modified, and displayed. You have the view, which is how you see the model. And you have the controller, which modifies the model.
    Your event handlers are part of the controller. They should change the model.
    Your paintComponent method is part of the view.
    So the event handlers should change some data, e.g., add a note that a circle should be displayed.
    Then your paintComponent method should look at the data and act accordingly -- e.g., see that there's a circle to be displayed, and display it.

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

  • Help: Factory Class using Inner Class and Private Constructor?

    The situation is as follows:
    I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
    I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
    Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?

    leesiulung wrote:
    As a second look, I was initially confused about your first implementation, but it now makes more sense.
    Let me make sure I understand this:
    - the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
    - the instance() method is the object factory
    - the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
    However, is a private inner class accessible in the outer class? Try it and see.
    How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
    How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
    public interface Game {
        String method();
    public class GameCollection {
        private static  class GameImpl implements Game {
            public String method() {
                return "GameImpl";
        public Game instance() {
            return new GameImpl();
        public static void main(String[] args) {
            GameCollection app = new GameCollection();
            Game game = app.instance();
            System.out.println(game.method());
    }Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game?

  • JDev Compiler Error? - Compiling inner classes

    This maybe just an interpretation of the language standard, but the compiler behavaviour is different from previous versions of JDeveloper and other Java IDE's, with no explanation found.
    Using JDeveloper 9.02.829 the following error is received.
    Error(13,9): class test$abc not found in class test.test
    when compiling the following class
    package test;
    public class test
    class abc { }
    public test()
    public void t ()
    abc a = new abc();
    The solution is to ensure the package name and class name are different (case sensitive) iff the class contains an inner class
    Whilst this can be done it can pose a problem porting older code into this release of JDeveloper, whilst no problem exists with other IDE's or older versions of the JDevloper IDE.
    The question is this a bug or a feature?

    This is a bug that got fixed a while back. The bug is with
    the fact that the class and the package have the same name.
    The bug is definitely fixed in 9.0.3 Preview Release which
    is currently available on OTN. 9.0.3 Production should be
    available anyday now.
    Michel

  • Compiling inner classes

    Hi,
    I have an applet with inner classes (the applet is contained in a single .java file). When I compile the applet, a number of *$*.class files are created for the inner classes. However, a friend of mine compiles the same .java file and he gets a single .class file. He can't see any files corresponding to the inner classes. My compiler is version 1.4.0, his is 1.4.2. Can you suggest how my friend can generate the *$*.class files corresponding to the inner classes?
    Thanks for your help.
    Miguel
    PS If the .jar file does not contain the *$*.class files, then appletviewer can't find the inner classes.

    Let me try again. My friend gets a single .class file.
    If he invokes the applet like this:
    <APPLet CODE="myapplet.class" WIDTH=100 HEIGHT=100>
    he has no problems at all.Because all the necessary files are there. Including the inner class files. Why he doesn't see them is another problem.
    However, if he puts his class file in myjar.jar and
    invokes the applet like this:
    <APPLet CODE="myapplet.class"
    ARCHIVE="myjar.jar"
    WIDTH=100 HEIGHT=100>
    then his inner classes are not found by appletviewer.Because he didn't put the inner class files in the jar. Why he didn't put them is another problem.
    There is abosolutely no other explanation I can see.

  • ER: Override Methods feature should detect anonymous inner class scope

    Hi,
    Given the following code:
    public class Class1 {
        public static void main(String[] args) {
            Thread t = new Thread() {
                // line 4
            t.start();
    }When the cursor is placed on line 4, activating the Override Method dialog (Source menu), should show Thread methods that I can override, in addition to Object methods. Currently only the method from class Object are being shown. The same treatment should also apply to local method inner classes. This happens with the latest 11g preview 3, and all previous versions.

    Hi,
    I'll file an ER
    Frank

  • Where is the anonymous class in this? (lotsa code)

    When I compile ThreadPool.java, I get three classes: ThreadPool.class, ThreadPool$WorkerThread.class, and ThreadPool$1.class. I understand the first two, but I can't figure out where the anonymous class is coming from. Could it be some kind of automatically-generated wrapper class caused by the fact that all accesses to the Queue object are within synchronized blocks? Curiosity attacks!
    Thanks,
    Krum
    ThreadPool.java:
    package krum.util;
    * A thread pool with a bounded task queue and fixed number of worker threads.
    public class ThreadPool {
       protected Queue queue;
    public ThreadPool(int threads, int taskQueueSize) {
       queue = new Queue(taskQueueSize);
       /* create the worker threads */
       for(int i = 0; i < threads; ++i) {
          Thread t = new Thread(new WorkerThread());
          t.setDaemon(true);
          t.start();
    * Queues a task to be executed by this ThreadPool.  If the task queue is
    * full, the task will run in the calling thread.  (Could easily be modified
    * to throw an exception instead.)
    public void doTask(Runnable task) {
       boolean added = false;
       synchronized(queue) {
          if(!queue.isFull()) {
             queue.add(task);
             added = true;
             queue.notify();
       if(!added) task.run();
    * Tests if the task queue is empty.  Useful if you want to wait for all
    * queued tasks to complete before terminating your program.
    public boolean queueEmpty() {
       synchronized(queue) {
          return queue.isEmpty();
    private class WorkerThread implements Runnable {
    public void run() {
       Runnable task;
       while(true) {
          task = null;
          synchronized(queue) {
             try {
                if(queue.isEmpty()) queue.wait();
                else task = (Runnable)queue.getNext();
             } catch(InterruptedException e) { break; }
          if(task != null) task.run();
    } /* end inner class WorkerThread */
    } /* end class ThreadPool */Queue.java:
    package krum.util;
    * Implements a FIFO queue for storage and retrieval of objects.  This class
    * is not synchronized.
    public class Queue {
         /** circular buffer containing queued objects */
         protected Object[] queue;
         /** index of next object to be returned */
         protected int nextReturn;
         /** index in which to store next object inserted */
         protected int nextInsert;
    public Queue(int capacity) {
         queue = new Object[capacity];
         nextInsert = 0;
         nextReturn = 0;
    public boolean isEmpty() { return(queue[nextReturn] == null); }
    public boolean isFull() { return(queue[nextInsert] != null); }
    public void add(Object obj) throws QueueException {
         if(queue[nextInsert] == null) {
              queue[nextInsert] = obj;
              ++nextInsert;
              nextInsert %= queue.length;
         } else throw new QueueException();
    public Object getNext() throws QueueException {
         if(queue[nextReturn] != null) {
              Object obj = queue[nextReturn];
              queue[nextReturn] = null;
              ++nextReturn;
              nextReturn %= queue.length;
              return obj;
         } else throw new QueueException();
    } /* end class Queue */QueueException.java:
    package krum.util;
    public class QueueException extends RuntimeException { }

    I can't explain why it happens, but I've seen this
    behaviour before. I found that it was to do with an
    inner class (WorkerThread in your code) having a
    private constructor - if I made my inner class
    constructor at least package (default) access, then
    the anonymous class was no longer created.
    The generated default constructor for a class has the
    same access modifier as the class, so in your example,
    the default constructor that the compiler generates is
    private.
    I suspect the problem will go away if you either:
    1. Remove the private modifier from the WorkerThread
    class declaration.
    or:
    2. Add a no-args constructor to the WorkerThread
    class, and don't specify an access modifier.Yes, the reason is the private constructor. After decompile using JAD, the reason seems to be: if a private inner class does not explicitly have any constructor, a default no-arguments private constructor is created, and seems this default constructor can't be accessed directly (in source code, it can). So, another no-private constructor (package accessible) is created automatically (with an argument of Object's type), and the
    new WorkThread();is actually like this:
    new WorkThread(null);
    private class WorkThread implements Runnable{
       private WorkThread(){}
       WorkThread(Object obj) {
          this();
    }and I would guess it's using anonymous class tech to achieve this like:
    new WorkThread(null) {
       WorkThread(Object obj){
          this();
    }The JLS should have specified this situation.

  • Subclassing and inner classes

    Hi there,
    I have an existing class "A", supplied by a third party, that contains a private inner class "I".
    I have subclassed "A" to a new class "B" to add new functionality, and I also want to replace the inner class "I" with new behaviour. The inner class "I" is invoked by methods within "A" that I have not overridden in "B". Replacing "I" appears to be impossible under these circumstances.
    My initial experiment was to create a new inner class "I" within "B" with the same name and signature as the "I" defined within "A", so...
    Class B extends A {
    private class I {}
    The code that invokes "I" is still within "A" and so my version of the "I" class is ignored, and the original "I" is invoked instead.
    Let's be clear about this, I am not surprised by this behaviour, I'm just wondering if there is any way I can get my "I" invoked by the methods in "A". If that is indeed impossible I will have to write new methods in "B" that override the invoking methods in "A".
    I did a search on the forums using the title I gave this topic, and got some fairly close hits, but nothing seemed to quite answer my question.
    Hope that all made sense. Thanks for any help.
    Regards,
    Tim

    When a class is compiled, all the references are resolved. So in the 'A' class file, a call to method someMethod() in inner class I is resolved as
    some.package.A$I.someMethod()
    Short of replacing the A$I class file, I don't know what you can do. (I think)

  • Inner Classes doubts

    Hi All,
    I am trying to learn Inner classes in Java. I am referring to the book Core Java by Horstmann and Cornell.
    I know that there are various types of inner classes namely:
    - Nested Inner classes
    - Local Inner classes
    - Annonymous Inner classes
    - static inner classes
    First I am on with Nested Inner classes :
    Following is the code which I am executing :
    package com.example.innerclass;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import javax.swing.JOptionPane;
    import javax.swing.Timer;
    public class InnerClassTest {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              TalkingClock clock = new TalkingClock(1000,true);
              clock.start();
    //          JOptionPane.showMessageDialog(null,"Quit Program");
    //          System.exit(0);
    class TalkingClock
         private int interval;
         private boolean beep;
         public TalkingClock(int interval, boolean beep){
              this.interval = interval;
              this.beep = beep;          
         public void start(){
              ActionListener listener = new TimePrinter();
              Timer t = new Timer(interval,listener);
              t.start();
         private class TimePrinter implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   Date now = new Date();
                   System.out.println("At the tone time is : "+now);
                   if(beep)
                        Toolkit.getDefaultToolkit().beep();
    }Following are my doubts :
    1. Why do we need to give the line
    JOptionPane.showMessageDialog(null,"Quit Program");
    System.exit(0);without this line the program doesn't show any output.
    2. I didn't understand this syntax.
    You can write inner object constructor more explicitly using the syntax. :
    outerObject.new InnerClass(construction parameters)
    For e.g.
    ActionListener listener = this.new TimePrinter();
    Here the outer class reference of the newly constructed TimePrinter object is set to this reference of the method that creates the inner class object. the this. qualifier is redundant. However, it is also possible to set the outer class reference to another object by explicilty naming it. For e.g if TimePrinter were a public inner class, you could construct a TimePrinter for any talking clock.
    TalkingClock jabberer = new TalkingClock(1000,true);
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    Please do help me understand this concept.
    Thanks
    Siddharth

    I have understood that this explanation :
    i) assuming that TimePrinter is an inner class of TalkingClock, that you'd need an instance of the later in order to create an instance of the former.Yes.
    Being a non-static inner class, it can not be instantiated out of context ... which context is the outer class.No. See my reply 11. The "context" is an instance of the outer class - it bears repeating.
    ii) jabberer is the outer instance that you are providing.Yes (more accurately it's a reference to an instance of the outer class, but that would be nit-picking).
    The left side is identifying the class, the right side is identifying the instanceNo.
    I'm not sure what you're calling left side and right side.
    If you're talking about both sides of the equals sign, then no, it's completely wrong.
    If you're talking about both sides of the "point" sign, then it's wrong too, just a bit less wrong.
    Let's revise this step by step (good thought process).
    1. in first line we are getting an outer class reference with this code
    TalkingClock jabberer = new TalkingClock(1000,true);
    this line is very natural and easily understood. Yes. The correct wording would be merely "we are getting a reference to an instance of the outer class". Sorry to insist densely.
    2. Now when we come to the second line, i.e. where we try to instantiate an inner class with this line of code
    TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    - I do understand the concept that we need an instance of outer class in order to create an instance of inner class as inner class is visible only to outer class.No. We need an instance of the outer class as the inner class is non-static, and by definition needs an instance of the outer class. That has nothing to do with visibility (public vs private vs...). Again, some words have special meanings in the Java world.
    - I also do understand that it cant be instantiated out of context. I see you like this expression, but it is too vague and misleads you. Please forget about it for a moment (no offense to otherwise helpful and knowledgeable abillconsl).
    - I also do understand that left side is identifying the class and right side is identifying the instance. ANDAgain I'm afraid of which "sides" you're talking about.
    - that in this line TalkingClock.TimePrinter listener = new TalkingClock().new TimePrinter();
    the outer class is anonymous (new TalkingClock()) as we don't require its name here Poor choice of words again. Anonymous classes do exist in Java, but are a totally different concept, that is not related to this line.
    - Also in this line TalkingClock.TimePrinter listener = jabberer.new TimePrinter();
    I understood the left side part i.e. TalkingClock.TimePrinter listener =
    We are attaching the outer class reference with the inner class that's absolutely understandable. Not at all!
    This just declares a variable listener, whose type is TalkingClock.TimePrinter (or more accurately com.example.innerclass.TalkingClock.TimePrinter).
    Then follows an assignment:
    WHAT I don't understand is the right hand side, i.e., the statement jabberer.new TimePrinter();
    1. I am unable to digest the fact that we can do something like anobject.new
    new is an operator that is used to instantiate an instance of an object. I am unable to digest that we can do x.new?See my previous reply. This is short-hand syntax Sun chose to pass a reference to an instance of the outer class (here, jabberer) to the constructor of the inner class. They could have chosen something else. Again, bear with it.
    I only know that we can do is new SomeClass(); AND NOT instance.new SomeClass();
    Now you know better:
    The second form is valid - only if SomeClass is a non-static inner class defined in a class of which instance is an instance.
    2. Is there something to this conceptually OR this is only a syntax and that I should learn it.
    I want to understand and grasp if there is some concept behind it rather than just learn and mug up. See my previous reply. Each instance of a non-static inner class stores a reference to an instance of the outer class. There must be a way (a syntax) to specify which instance (of the outer class) should be stored in the instance (of the inner class).
    This particular syntax is just a syntax, the "concept" is that the instance of the inner class stores a (unmodifiable) reference to the instance of the outer class that was specified when the instance of the inner class was created.
    I don't know if that deserves to be called a concept, but that's an interesting thing to keep in mind (there are some not-so-obvious implications in terms of, e.g. garbage collection).
    Best regards.
    J.

Maybe you are looking for