Java Inner classes within the Threading paradigm

Hi all.
Im familiar with static nested classes, method local classes, inner classes and anonymous classes.
But what I am a little perplexed by, is when exactly to use inner classes or static nested classes? (forgetting anonymous classes and method local classes).
I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
Also you typically find nested classes within the Threading paradigm, but why?
I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
use this class when constructing a new Thread.
Any clarification would be greatly received.
Thanks and Happy Friday.

Boeing-737 wrote:
I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
I was going to provide some reasons, but when I read the article I found they were already there. Following the DRY principle I'm going to let the article speak for itself.
Also you typically find nested classes within the Threading paradigm, but why?No, I don't. If that's where you typically find them then you haven't had a varied experience.
I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
use this class when constructing a new Thread.So carry on doing that, if it works for you.

Similar Messages

  • Parametric inner classes have the same parametric tpye?

    The qestion I have is:
    If you have a parametric inner class with the name of the type parameter the same as the one of the parametric "outer" class. Are they the same?
    I think they should be, but I just made an obeservation that they probably aren't.
    The follwing code does not compile
    public class POC<E> {
        public Iterator<E> iterator() {
            return null;
        private class Magic<E> {
            private Iterator<E> iterator;
            public Magic() {
                Magic.this.iterator = POC.this.iterator();
    }What actually bugs me, is the error I got:
    incompatible types
    found: java.uti.Iterator<E>
    required: java.util.Iterator<E>
    hu? To me this looks like a match.
    I could get it to compile with an Instance of Iterator<E> passed to the constructor in stead of getting it by myself.
    And I use 1.5rc

    Probably because types E and T are not correlated:
    public class POC<E> {
        public Iterator<E> iterator() {
            return null;
        private class Magic<T> {
            private Iterator<T> iterator;
            public Magic() {
                Magic.this.iterator = POC.this.iterator();
    }The error message in this case is:
    POC.java: : incompatible types
    found   : java.util.Iterator<E>
    required: java.util.Iterator<T>
                Magic.this.iterator = POC.this.iterator();I've succeded to compile the following two programs:
    //1.
    public class POC<E> {
        public Iterator<E> iterator() {
            return null;
        private class Magic<E> {
            private Iterator<E> iterator;
            public Magic() {
                POC<E>  p = new POC<E>();
                iterator = p.iterator();
    // 2.
    public class POC<E> {
        public static <E> Iterator<E> iterator() {
            return null;
        private static class Magic<E> {
            private Iterator<E> iterator;
            public Magic() {
                iterator = POC.iterator();
    }Which one suits you best?
    Best regards,
    Andrej

  • Java inner classes

    G'day
    How does one - in CF - refer to an inner class (ClassFoo.Bar)
    of a given
    class (ClassFoo), when the constructor of ClassFoo takes an
    argument of
    type ClassFoo.Bar?
    For example the first, third,fourth and fifth constructors
    shown here:
    http://tinyurl.com/hfg9s
    (org.apache.lucene.document.Field).
    Any ideas?
    Adam

    >is the reason you can't use another "." because it is not
    a property of Field
    Thats my understanding, yes.
    > what does the $ represent
    Its part of the class name. It has to do with how java
    compiles the classes. It creates one file for the outer class and
    one for the inner class. The naming convention for inner class
    files is usually "OuterClassName$InnerClassName.class". So the
    class name passed to createObject() becomes
    bar = createObject("java", "OuterClassName$InnerClassName");

  • Accessing object of the main class from the thread

    Hi, I'm having problem accessing object of the main class from the thread. I have only one Thread and I'm calling log.append() from the Thread. Object log is defined and inicialized in the main class like this:
    public Text log;  // Text is SWT component
    log = new Text(...);Here is a Thread code:
    ...while((line = br.readLine())!=null) {
         try {
              log.append(line + "\r\n");
         } catch (SWTException swte) {
              ErrorMsg("SWT error: "+swte.getMessage());
    }Error is: org.eclipse.swt.SWTException: Invalid thread access
    When I replace log.append(...) with System.out.println(..) it works just fine, so my question is do the log.append(..) the right way.

    This is NOT a Java problem but a SWT specific issue.
    It is listed on the SWT FAQ page http://www.eclipse.org/swt/faq.php#uithread
    For more help with this you need to ask your question on a SWT specific forum, there is not a thing in these forums. This advice isn't just about SWT by the way but for all specific API exceptions/problems. You should take those questions to the forum or mailing list for that API. This forum is for general problems and exceptions arising from using the "core" Java libraries.

  • Tool to create Java Object classes using the Database Tables

    Hi,
    Is their any tools or utility available to create the Java Object Classes using the Database Tables as input.
    Lets Say I am having the Employee, Employee_Salary tables in the Database.The utility has to create the Java Object classes with the relation.
    Please Help...
    Thx..

    Hm, for generating regular Java classes I wouldn't know one from memory. But I suggest you start searching in for example the Eclipse marketspace for a third party plugin that can do it. If all fail, you could always use Hibernate Tools from the Jboss Tools Eclipse plugin set to generate Hibernate/JPA entities and then strip the annotations from them to turn them into regular POJO classes.
    How many tables are we talking about anyway? It might be less effort to just create the classes with properties and then use an IDE to generate getters and setters for them.

  • I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with emails from this thread. I used the action within the thread that says stop following but appears to have no effect I stil

    I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with  emails from this thread. I used the action within the thread that says stop following but appears to have no effect I still keep  getting from 5 to 20 emails daily. Please help!!!!!!!

    This may be helpful: How do I disable email notifications?

  • Applet inside a JAR: Cannot access other classes within the JAR

    Hello,
    Description
    Web app + applet (packaged in a JAR)
    I have followed this tutorial
    JAR contents
    package mypackage
    SimpleApplet.class
    SimpleObj.class
    _"SimpleApplet" uses "SimpleObj"_
    package mypackage;
    public class SimpleApplet extends JApplet {
        @Override
        public void init() {
            SimpleObj obj = new SimpleObj();
    HTML code
    <applet archive="SimpleApplet.jar" codebase="." code="mypackage.SimpleApplet.class" width="800" height="600" />
    SimpleObj cannot be found (Java Console)
    java.lang.NoClassDefFoundError: mypackage/SimpleObj
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.newInstance0(Unknown Source)
    at java.lang.Class.newInstance(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager.createApplet(Unknown Source)
    at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.ClassNotFoundException: mypackage.SimpleObj
    at sun.plugin2.applet.Applet2ClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    ... 8 more
    Caused by: java.io.IOException: open HTTP connection failed:*http://localhost:8080/SimpleApp/mypackage/SimpleObj.class*
    at sun.plugin2.applet.Applet2ClassLoader.getBytes(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader.access$000(Unknown Source)
    at sun.plugin2.applet.Applet2ClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    ... 12 more
    Exception: java.lang.NoClassDefFoundError: mypackage/SimpleObj
    It looks like JRE does not search for the SimpleObj class inside the JAR, but tries to get it from the server...
    Any ideas?
    Thanks in advance,
    Gerard
    Edited by: gsoldevila on Dec 10, 2008 2:05 AM

    misread, deleted
    Edited by: atmguy on Dec 10, 2008 1:12 PM

  • Call Class within the Database

    I don't know if this is the right place to post, but. I'm trying to create an Applet that references a JAVA class stored in the database. My code looks something like this:
    <applet code="Hello.class" codebase="http://www.somesite.com/pls/dad/" width="150" height="30"></applet>
    Hello.class is stored within a 10g database. The codebase is a vitural url that connects to a schema within the database. Can this be done?? and How??

    Please elaborate. I believe the answer is yes, but it's not entirely clear what you mean.
    - Phil

  • How to override a method in an inner class of the super class

    I have a rather horribly written class, which I need to adapt. I could simply do this if I could override a method in one of it's inner classes. My plan then was to extend the original class, and override the method in question. But here I am struggling.
    The code below is representative of my situation.
    public class ClassA
       ValueChecks vc = null;
       /** Creates a new instance of Main */
       public ClassA()
          System.out.println("ClassA Constructor");
          vc = new ValueChecks();
          vc.checkMaximum();
         // I want this to call the overridden method, but it does not, it seems to call
         // the method in this class. probably because vc belongs to this class
          this.vc.checkMinimum();
          this.myMethod();
       protected void myMethod()
          System.out.println("myMethod(SUPER)");
       protected class ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUPER)");
             return true;
          protected boolean checkMaximum()
             return false;
    }I have extended ClassA, call it ClassASub, and it is this Class which I instantiate. The constructor in ClassASub obviously calls the constructor in ClassA. I want to override the checkMinimum() method in ValueChecks, but the above code always calls the method in ClassA. The ClassASub code looks like this
    public class ClassASub extends ClassA
       public ClassAInner cias;
       /** Creates a new instance of Main */
       public ClassASub()
          System.out.println("ClassASub Constructor");
       protected void myMethod()
          System.out.println("myMethod(SUB)");
       protected class ValueChecks extends ClassA.ValueChecks
          protected boolean checkMinimum()
             System.out.println("ValueChecks.checkMinimum (SUB)");
             return true;
    }The method myMethod seems to be suitably overridden, but I cannot override the checkMinimum() method.
    I think this is a stupid problem to do with how the ValueChecks class is instantiated. I think I need to create an instance of ValueChecks in ClassASub, and pass a reference to it into ClassA. But this will upset the way ClassA works. Could somebody enlighten me please.

    vc = new ValueChecks();vc is a ValueChecks object. No matter whether you subclass ValueChecks or not, vc is always of this type, per this line of code.
    // I want this to call the overridden method, but it does not, it seems to > call
    // the method in this class. probably because vc belongs to this class
    this.vc.checkMinimum();No, it's because again vc references a ValueChecks object, because it was created as such.
    And when I say ValueChecks, I mean the original class, not the one you tried to create by the same name, attempting to override the original.

  • Are inner classes used the same way as derived classes?

    Hi,
    I got myself a bit confused when I came across inner and derived classes.
    However, I know that the syntax for both are different.
    For inner classes:
    class OuterClass {
    class NestedClass {
    For inheritance:
    class ClassA {
    class ClassB extends ClassA {
    But I justed wanted to clarify if there's differences in the usage of either one?
    Thanks.

    Nat7 wrote:
    Hi,
    I got myself a bit confused when I came across inner and derived classes.
    However, I know that the syntax for both are different.That should be a clue. They are entirely different things.
    What this question suggests to me is that you don't understand what a derived class is or you don't understand what an inner class is.
    Perhaps if you gave us your definitions of them we could fix this.

  • 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();
    }

  • JavaFX accessing Java Inner Classes

    We have LOTS of common Java classes that look like this...
    public class X {
        public class Y {
            public static final String Z = "ZzZZZzzZzzZzzZz";
    }So in JAVA we can access them like this...
    public String z = X.Y.Z;But in JavaFX I CAN'T do this...
    var z : X.Y.Z;The compiler says +"non-static class com.myproject.X.Y cannot be referenced from a static context"+
    Tell me it aint so, please :)

    Galien, I doubt AndrewHughes can / want to change all the existing Java classes...
    I tried to reproduce (I did) and found a workaround...
    Java class (X.java):
    public class X
        public static final String ZX = "ZzZZZzzZzzZzzZzXX";
        public class Y
            public static final String ZY = "ZzZZZzzZzzZzzZzYY";
        public static void main(String[] args)
          new A();
    class A
      A()
        System.out.println(X.Y.ZY);
    }OK, it works...
    JavaFX code: var z = X.Y.Z;(and not var z: X.Y.Z; since Z isn't a type...) Error "+non-static class X.Y cannot be referenced from a static context+". Mmmm...
    Trying var z = X.ZX; works, of course.
    Looking at the generated class files, I thought of a workaround: var z = X$Y.ZY;Yay! it works! :-D

  • Possible have the an inner class named the same as an outer class?

    Is there some workaround for this issue? I have some code generated by JAXB that won't compile because of a situation like this.
    public class Class1 {
        public Class1() { }
        public static class Quantity {
            public Quantity() { }
            public static class Year {
                public Year() { }
                public static class Quantity {
                    public Quantity() { }
    }When I remove the inner-most Quantity class, the compiler creates:
    Class1.class
    Class1$Quantity.class
    Class1$Quantity.Year.class

    Try a different name for the inner class. I'm sure there is no dearth of names.

  • How to retrieve hashmap Values in other class within the same package.

    I have created two class ie A and B.
    In A class I have created one hashmap and stored some keys and values.
    But i want to retrieve that values in class B.
    So can any one can give any code ,so that i will try on Eclipse IDE

    Maybe anything. I'm not that interested. It's Java programming 101, about 10 minutes into the first class.

  • Java inner class access specifiers

    public class MyClass1 {
    public static void main(String argv[]){ }
    /*Modifier at XX */ class MyInner {}
    What modifiers would be legal at XX in the above code?
    1) public
    2) private
    3) static
    4) friend

    Iam a newbie to javaI don't care. I still assume you have a brain and expect you to use it.
    and iam struck with this
    question, iam getting a compile time error for any
    access specifiers mentioned as options, but the
    answers given by my superior are 1,2,3, are
    correct..Then you made a typo or whatever. Make sure you eliminate the problems that are not "illegal access modifier" errors.
    What good is knowing the reply to this if you can't even write an example?

Maybe you are looking for

  • Personal File Sharing

    I have a small office network setup with 8 macs. I'm currently using personal file sharing within the network. Sometimes I can not tell who is connected to which machine at any given time. When I go to shut my machine down, I'll get the message "Ther

  • SSO For Jabber 10.5

    Hi, Has anyone Configured SSO for Jabber successfully with CUCM 10.5 Version. I am getting following error after Exchanging Meta Data with ADFS Server. Can anyone suggest further troubleshooting steps. Of if there is any detailed guide for SSO with j

  • Folders on NAS read-only. Can't change

    I have a buffalo linkstation pro duo NAS. It is formatted in XFS. It seems that randomly some folders have been changed to read-only, when they were previously read-write. I have one folder that is stuck in a read-only state. The folder contains some

  • Batch change

    Is there a way to batch change the image date?

  • Editing Video in PS CS4 Extended

    I am unable to open video in PS CS4 Extended. I tried two different extensions, .mpg and .mov. I get an error that says the file can not be opened. Yes, I am sure I have PS Extended. Thanks!