Doubt in inner classes

public class Outer
           public static void main(String argv[])
                     Outer o=new Outer(); //1                    
                     Inner i =o.new Inner(); //2
                     //Inner i =new Inner();  //3
     i.showName();   
         public      class Inner{   
                void showName()
        System.out.println("hi");            
      }//End of Inner class
}I have few doubt regrd the above program..
1)when i create an inner class instance as in line 3,..Iam having an err like
non-static variable this cannot be referenced from a static context.. Bcas Inner is a non static member of class Outer it cant be referred without an instance of Outer as in line 2.. But my doubt is why it doesnt give such error (of static context issue) in the case of line 1...its a silly dbt but iam confused ...
2..Can we refer the inner class without outer class like in line 2., I have used
Inner without Outer ..is this ok... or shuld we use as
Outer.Inner i =o.new Inner(); //2
3)In the above line We r associating the instance of inner class with the instance of outer class and the type of inner class with the type of outer class (Outer.Inner )..wht does this mean..
can anyone pls help me understand this..
thnx.
mysha..

public class Outer
public static void main(String argv[])
Outer o=new Outer(); //1
er o=new Outer(); //1                    
Inner i =o.new Inner(); //2
//Inner i =new Inner();  //3
     i.showName();   
public      class Inner{   
void showName()
        System.out.println("hi");            
}//End of Inner class
}I have few doubt regrd the above program..
1)when i create an inner class instance as in line
3,..Iam having an err like
non-static variable this cannot be referenced from a
static context.. Bcas Inner is a non static member of
class Outer it cant be referred without an instance
of Outer as in line 2.. But my doubt is why it doesnt
give such error (of static context issue) in the case
of line 1...its a silly dbt but iam confused ...
Static methods of a class exist as soon as Java loads the class. Regular, or non-static, methods of a class belong to an object and only come into existence after you create an object of the class. Regular methods are called by an object. Static members are called using the class name.
Now, examine this simple program:
class Apple
     private String color;
     public Apple(String color)
          this.color = color;
     public void show()
          System.out.println("apple color: " + color);
     public static void greeting()
          System.out.println("Hello from the Apple class.");
public class  Demo
     public static void main(String[] args)
          Apple.greeting();  //1
          Apple a = new Apple("red");  //2
}After the Apple class loads, any static methods in the class exist. Since greeting() is a static method of the Apple class, it can be called in line 1 before any Apple objects exist. But, what about line 2? How can the Apple constructor with the String parameter, which is a method in the Apple class, be called? The constructor isn't declared as a static, so it shouldn't exist in that regard, and no objects of the class exist. So, when and how did the constructor come into existence. That seems to be the question you're struggling with. I think the answer is: a constructor sort of acts like a static method. In order to be able to call a constructor, the constructor must exist as soon as the class loads and before any objects exist. The result is, you can call a constructor at any time.
I think your example is similar to my example, but you only have one class:
public class Outer
public static void main(String argv[])
Outer o=new Outer(); //1
}After Java loads Outer, any static methods in Outer exist. Since main() is a static method, it exists. Subsequently, java calls the static main() method to begin execution of your program. In line 1, you call the default constructor for Outer. The default constructor isn't static, so it shouldn't exist, but just like the constructor in my example above, the default constructor acts like a static method, and therefore you can call it without getting an error.
Inner i =o.new Inner(); //2
2..Can we refer the inner class without outer class
like in line 2., I have used
Inner without Outer ..is this ok... or shuld we use
as
Outer.Inner i =o.new Inner(); //2
I'm not sure what the difference is. In both cases you end up with an object that was created with the expression:
o.new Inner()
you just have a different type for your object, i.e. Outer.Inner versus Inner.
3)In the above line We r associating the instance of
inner class with the instance of outer class and the
type of inner class with the type of outer class
(Outer.Inner )..wht does this mean..
can anyone pls help me understand this..
I think you said it: it means you have an Inner object that is "associated" with an Outer object. Like any other regular member in the Outer class, Inner can refer to any members of Outer. (A static member of Outer can't refer to regular members of Outer because static members exist before any objects exist, and when no objects exist, the regular members don't exist.) That means an Outer object must exist before you can create an Inner object.

Similar Messages

  • Doubt in Inner class

    hi ,
    i have a doubt. How we can access a Inner class name by the outer class name using the Dot(.) operator .
    For example if we want to refer to the Inner class in some other class
    then we must say "OuterClass.InnerClass".
    This type of syntex is ment for the static methods in a class.
    Thus can we assume that Inner class is also a type of static member.
    If not then please explain the syntex.
    i am also not getting the way we create object of the Inner class object in some other class . (i mean to say the logic behind the syntex)
    i.e
    OuterClass Ob1=new OuterClass();
    OuterClass.InnerClass InnOb=Ob1.new InnerClass();
    Cna any one please help me out.
    Regards
    Arunabh

    Hi,
    Inner classes are used to create some functionality in terms of OO way. Like you want to have event handling which will work only for designated GUI classes, then we can make use of Innner class.
    Within a outer classes we do not require any reference of outer object BUT, if you want to access Inner class object outside the class then only we need a reference of Outer object so that we instantitate Inner class object.
    thanks,
    Sandeep

  • A doubt on Inner classes

    Hi,
    The below program throws a compilation error saying "The method fn() in the type Outer.Inner is not applicable for the arguments (String)". I am expecting it to call the private String fn(String in) method on Outer class. This might be silly, but I am not able to find the reason why?
    public class Outer {
    private String fn(String in){
    return in+"outer";
    class Inner{
    private String fn(){
    return fn("");
    Can anyone please shed some light on it?
    Thanks in advance,
    Jose John

    TPD Opitz-Consulting com wrote:
    EJP wrote:
    The reason is that the inner fn(), not being an override (i.e. not taking the same arguments), is instead an overload (different arguments), and overloads hide what they overload in outer scopes.This is wrong. No inheritance is involved here.I fail to see where EJP actually mentions inheritance.
    The point may be that you cannot access a non static method without an object. YOU are wrong. The Eclipse quickfix is simply the standard way of referring to a member of an outer class even when the property/method is 'overlapped' by one of the inner class.

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

  • Adding inner class object

    Hello to all
    I have one doubt regarding eventhandling. Consider i am having one class named outer which extends applet and with in outer class i am having one class inner which extends panel.
    Now when i try to add the inner class object in action performed of outer
    class it doesnt get added. How to overcome this.
    Eventhough sometimes it gets added it shouldnot appear for the first time. After resizing the window only it gets displayed.
    How to over come this.
    This is my coding
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JApplet implements ActionListener{
         JButton b1;
         Container c;
         public void init()
              c=getContentPane();
              b1=new JButton("First");
              c.add(b1,BorderLayout.NORTH);
              b1.addActionListener(this);
         public void actionPerformed(ActionEvent ae)
              System.out.println("Working");
              c.add(new panel());
         class panel extends JPanel
              int a=5;
              JLabel l=new JLabel("ADSF");
              public panel()
                   add(new JButton("ASDFASDFs"));
                   add(l);
              /*public void paint(Graphics g)
                   g.drawString("ASDFASDF123123123123",20,20);
    }

    You could try being more specific when you add ie
    c.add(new panel(), BorderLayout.CENTER);

  • Anonynous Inner Classes

    Hi, i was goin through Anonymous Inner Classes, i have a doubt.
    Please go through the snippet below.
    class Anonymous
         public void pop()
              System.out.println("Original pop");
    class Sub
         Anonymous a = new Anonymous(){
              public void pop()
                   System.out.println("Anonymous pop");
    class AnonymousEg
         public static void main(String[] args)
    How do i access pop() method declared in the class Sub.
    Thanx in advance.

    I want to access it from main method.
    public static void main(String args[])
    Anonymous a = new Anonymous();
    a.pop();
    Here the output will be "Original pop".
    But how do i access the pop() method which is there
    in 'Sub' class so that the output is 'Anonymous pop'
    I think i had placed it more clearly now.See relpy #2.
    Your Sub isn't a subclass and isn't related to the top level Anonymous class at all. Create an Sub instance, and call a.pop on that instance.
    Kaj

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

  • Problem with final variables and inner classes

    variables accessed by inner classes need to be final. Else it gives compilation error. Such clases work finw from prompt. But when I try to run such classes through webstart it gives me error/exception for those final variables being accessed from inner class.
    Is there any solution to this?
    Exception is:
    java.lang.ClassFormatError: com/icorbroker/fx/client/screens/batchorder/BatchOrderFrame$2 (Illegal Variable name " val$l_table")
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
         at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.access$1(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderFrame.<init>(BatchOrderFrame.java:217)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.createView(BatchOrderViewController.java:150)
         at com.icorbroker.fx.client.screens.RealTimeViewController.initialize(RealTimeViewController.java:23)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.<init>(BatchOrderViewController.java:62)
         at com.icorbroker.fx.client.screens.displayelements.DisplayPanel$3.mousePressed(DisplayPanel.java:267)
         at java.awt.Component.processMouseEvent(Component.java:5131)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3162)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         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)

    I've also been having the same problem. The only work-around seems to be to slightly change the code, recompile & hope it works. See http://forum.java.sun.com/thread.jsp?forum=38&thread=372291

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

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

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

  • Problem with constructor of inner class.

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

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

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

  • Threaded inner classes & heap memory exhaustion

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

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

  • Compiler error when useing switch statements in an inner class

    I have defined several constants in a class and want to use this constans also in an inner class.
    All the constants are defined as private static final int.
    All works fine except when useing the switch statement in the inner class. I get the compiler error ""constant expression required". If I change the definition from private static final to protected static final it works, but why?
    What's the difference?
    Look at an example:
    public class Switchtest
       private static final int AA = 0;     
       protected static final int BB = 1;     
       private static int i = 0;
       public Switchtest()
          i = 0; // <- OK
          switch(i)
             case AA: break; //<- OK, funny no problem
             case BB: break; //<- OK
             default: break;
      private class InnerClass
          public InnerClass()
             i = 0; // <- OK: is accessible
             if (AA == i) // <- OK: AA is seen by the inner class; i  is also accessible
                i = AA + 1;
             switch(i)
                case AA: break; // <- STRANGE?! Fail: Constant expression required
                case BB: break; // <- OK
                default: break;
    }Thank's a lot for an explanation.

    Just a though:
    Maybe some subclass of Switchtest could decalare its own variable AA that is not final, but it can not declare its own BB because it is visible from the superclass. Therefore the compiler can not know for sure that AA is final.

  • Passing Inner class name as parameter

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

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

  • How to call inner class method in one java file from another java file?

    hello guyz, i m tryin to access an inner class method defined in one class from another class... i m posting the code too wit error. plz help me out.
    // test1.java
    public class test1
         public test1()
              test t = new test();
         public class test
              test()
              public int geti()
                   int i=10;
                   return i;
    // test2.java
    class test2
         public static void main(String[] args)
              test1 t1 = new test1();
              System.out.println(t1.t.i);
    i m getting error as
    test2.java:7: cannot resolve symbol
    symbol : variable t
    location: class test1
              System.out.println(t1.t.geti());
    ^

    There are various ways to define and use nested classes. Here is a common pattern. The inner class is private but implements an interface visible to the client. The enclosing class provides a factory method to create instances of the inner class.
    interface I {
        void method();
    class Outer {
        private String name;
        public Outer(String name) {
            this.name = name;
        public I createInner() {
            return new Inner();
        private class Inner implements I {
            public void method() {
                System.out.format("Enclosing object's name is %s%n", name);
    public class Demo {
        public static void main(String[] args) {
            Outer outer = new Outer("Otto");
            I junior = outer.createInner();
            junior.method();
    }

Maybe you are looking for

  • Application Server : File writes only 255 characters

    Hi Friends, I am trying to writes data to application server file . My line size is 1100 charqacters. When I use open dataset for output in text mode encoding default and transfer contents to file. I am only able to write contents upto 255 characters

  • ME21n & MIRO problem

    Dear Experts, We are using Ecc 6.0 here we found some problem during PO and MIRO T Code In ME21N we face tax code is blank in some cases and po is saved we can take GR and MIRO successfully how is it possible i can't understand. During MIRO one can c

  • Transport XI System Landscape Directory Contents from Production to Quality

    Hi I want to transport SLD contents from my production environment to the quality environment. I could see a link in of export in the SLD Administration page, will that help me. I think that link will allow me to transfer whole contents however I wan

  • A SMALL EXAMPLE CODE FOR MUTATING ERROR

    create or replace trigger TRG_T1 before insert on T1 begin insert into T1 values(2); end; IF I TRY TO INSERT INTO T1 TABLE I GET A MUTATING ERROR HOW CAN I SOLVE??????

  • Replacing FRM messages

    Hello, I want to replace a FRM message but when I use the Headstart Foundation Application Messages I can't see the 3 check box below Severity pop list. Why ? I use Oracle 9i Designer with Headstart 9i (652). Thank you. Antoine LEFEBVRE.