Inner classes use

what is the main goal behind using inner classes in java design

The best thing about inner classes in Java (something they missed in the C++ spec) is that a non-static inner class has direct access to everything in the containing class without the need to maintain an explicit reference.
That makes inner class instances ideal as a kind of "delegate" from the main object into another context, e.g. to generate several ActionListener objects to be added to various gadgets, or as an Iterator which moves through some child elements.

Similar Messages

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Instantiation an inner class using reflection

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

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

  • Debugging Inner Class using jdb

    Hi
    I am using JDK 1.3.1 on solaris and observe that the java debugger does not stop at "Inner class" methods. Is there any way to make jdb (from command line) stop inside the "inner class"?

    I had the following code (similar to the example you gave) :
    package test;
    public class Outer {
      public Outer() {
        Inner i = new Inner();
      static public void main(String[] args) {
        Outer o = new Outer();
      public class Inner {
        public Inner() {
          System.out.println("Inner");
          Runnable Runner = new Runnable() {              
         public void run() {
           System.out.println("Runner");
          Runner.run();  
    }Which compiled into :
    Outer.class
    Outer$Inner.class
    Outer$1.class
    And to stop at the line System.out.println("Runner"); I could use stop at test.Outer$1:14 or stop in test.Outer$1.run(). So it seems that you need to look at the compiled .class name and use that.

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

  • Program Design Problem: Inner Class use verse interacting seperate classes?

    i am designing a GUI based program that needs to have 2+ windows that interact with each other. In my original design there were just two windows: the World display, and the tile choser (this is for 2D map editing). Because there were only 2, I made them both inner classes of another class. The top level class's fields were how I got the two windows to interact.
    Now I am adding more tile choser esque windows and it is getting very confusing and the amount of Fields is getting ridiculous and the whole thing isnt very OO.
    I thought about splitting up the World Display window and the Tile Choser window into two different classes and just have multiple instances of the Tile Choser class for the additional windows.
    The problem is the interaction. I could pass all of the variables that both classes require to constructers and set up lots and lots of get and set methods, but then that seems to destroy the whole idea of two classes. The whole project is getting really messy.
    Any thoughts?
    I know that was a jarbled explanation so just ask about any part that might be unclear

    Create an object that represents the state being manipulated. The model.
    Create methods to modify that data. Not getters/setters, but controllers. If it's a map, then maybe a method would be "addTown" or something. This represents the controller.
    Create methods to render the data graphically. The views.
    Pass this object to GUI widgets, or reference it from inner event handlers.

  • When  we going to use static inner class

    Hi
    when we r going use static inner class
    inner classes use for to create adaptorclasses that implement an interface.
    what about Static inner class
    if possible give some examples
    Thanks in adv

    static inner classes are used when the inner class does not require to access the encompassing class's variables/methods. By default non-static inner classes obtain a reference to the outer class instance through which they access the outer class variables and methods
    ram.

  • Generics and inner classes?

    How can I say my inner class uses the same type as it's genericised host class?
    Should I just not declare a "generic" type in the inner class?
    The code
    public class LinkedList<E> implements java.util.List<E>
      ... code omitted for brevity ...
       * An internal implementation of java.util.Iterator.
      private class Iterator<E> implements java.util.Iterator<E> {
        protected Node<E> current;
        public Iterator() {
          this.current = head; // error here
      ... code omitted for brevity ...
    produces the compiler error
    C:\Java\home\src\linkedlist\LinkedList.java:59: incompatible types
    found   : linkedlist.LinkedList.Node<E>
    required: linkedlist.LinkedList.Node<E>
          this.current = head;
                         ^I understand the meaning of the compiler error... it's effectively saying that "E" is not the same type within in the Iterator class as it is in the parent LinkedList class... What I don't understand is how to make E the same type within the Iterator... if I just leave the <E> off of Iterator<E> then it throws "unchecked operation" warnings... do I just have to put up with these warnings... but no that can't be right because java.util.LinkedList has an iterator and it's not throwing unchecked operation compiler warnings... so there has to be a way...
    Thanx all. Keith.

    One more dumbshit question...
    Is there a way to do this without the warnings OR the @SuppressWarnings({"unchecked"})
       * Returns the index of the last occurrence of the specified element in this
       * list, or -1 if this list does not contain the element.
      //@SuppressWarnings({"unchecked"})
      public int lastIndexOf(Object object) {
        int i = 0;
        int last = -1;
        for(Node<E> node=this.head.next; node!=null; node=node.next) {
          if (node.item.equals((E) object)) {
            last = i;
          i++;
        return(last);
    produces the warning
    C:\Java\home\src\linkedlist\LinkedList.java:313: warning: [unchecked] unchecked cast
    found   : java.lang.Object
    required: E
          if (node.item.equals((E) object)) {
                                   ^... remembering that List specifies +public int lastIndexOf(Object object);+ as taking a raw Object, not E element, as I would have expected.
    Thanx all. Keith.

  • Mapping inner class in mapping workbench

    A project needs to work with inner classes and map these inner classes using TopLink Mapping Workbench. Is this supported? Thanks.
    Haiwie

    Karen,
    Thanks for your response.
    I tried with 9.0.4.4, and it worked. I had to use 'Use Factory' option for Instantiation; the mapping workbench complains about the default instantiation setting, i.e. 'Use Default Constructor'.
    Haiwei

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

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

  • Trying to use super class's methods from an anonymous inner class

    Hi all,
    I have one class with some methods, and a second class which inherits from the first. The second class contains a method which starts up a thread, which is an anonymous inner class. Inside this inner class, I want to call a method from my first class. How can I do this?
    If I just call the method, it will use the second class's version of the method. However, if I use "super," it will try to find that method in the Thread class (it's own super class) and complain.
    Any suggestions?
    Code:
    public class TopClass
         public void doSomething(){
              // do something
    =============================
    public class LowerClass extends TopClass
         // overrides TopClass's doSomething.
         public void doSomething(){
              // do something
         public void testThread(){
              Thread t = new Thread(){
                   public void run(){
                        doSomething();               //fine
                        super.doSomething();          //WRONG: searches class Thread for doSomething...
              t.start();
    }

    Classes frequently call the un-overridden versions of methods from their superclasses. That's that the super keyword is for, if I'm not mistaken.You're not mistaken about the keyword, but you're not calling the superclass method from a subclass. Your anonymous inner class is not a subtype of TopLevel. It's a subtype of Thread.
    Here it is no different, except that I happen to be in a thread at the time.It's vastly different, since you're attempting to call the method from an unrelated class; i.e., Thread.
    I could also be in a button's action listener, for example. It seems natural to me that if I can do it in a method, I should be able to do it within an anonymous inner class which is inside a method.If you were in an button's action listener and needed to call a superclass' implementation of a method overridden in the button, I'd have the same questions about your design. It seems smelly to me.
    ~

  • When to use Nested Class/Inner Classes ?

    I am not very clear, when to use nested/inner classes..
    The scenario is :-
    class ABC
    //ABC need to store multiple instance of class XYZ
    class XYZ
    int member1;
    int member2;
    One approach is
    class ABC
    class XYZ
    //vector of class XYZ instances is stored in class-ABC
    or another approach is Class XYZ can be in separate JAVA file.
    Query:-
    1) Is there any difference between nested or Inner class...or are they same?
    2) When should they be used....Is it good to use in above scenario.
    3) What are the disadvtanges/advantages of using the Nested
    class.

    Query:-
    1) Is there any difference between nested or Inner
    class...or are they same?I really don't get it. Yes there is a difference between having an inner class, and a class in a separate file, but a nested class is an inner class.
    2) When should they be used....Is it good to use in
    above scenario.To write an inner class is a design decision. Do other classes need to know about the class XYZ or not? Do the XYZ class need to know about the inner working of the ABC class? How complex is the XYZ class etc.
    >
    3) What are the disadvtanges/advantages of using the
    Nested
    class.See above.
    /Kaj

  • How to use a static inner class?

    what's the implication of identifier "static" before an inner class.Thank you.

    not sure what implication is, due to my poor vocabulary. But here's an uuh... "example" of a static inner class:
    public class Example {
         static class AnotherClass {
    }There you have class "Example" with the static inner class "AnotherClass." If you wanted to use "AnotherClass" you would do something like:
    public class Whatever {
         Example.AnotherClass ac = new Example.AnotherClass();
    }I don't think I'm mistaken there, but if I am someone please correct me.

  • Help,about why we use inner class?

    Hi,
    when i read "java Tutorial"
    i found there is one chapter about inner class .
    i copy it down as follow.
    the context is about there is a class Stack, and this class want to implement some function of interface Iterator,but as the book said
    we should not let class Stack implement the Iterator directly, we should add a inner class inside the Stack .
    i know it's very import ,but i still can not understand the reason why add a inner class here.
    hope somebody can explain it a little more for me or give an example.
    thank in advance!
    Iterator defines the interface for stepping once through the elements within an ordered set in order. You use it like this:
    while (hasNext()) {
    next();
    The Stack class itself should not implement the Iterator interface, because of certain limitations imposed by the API of the Iterator interface: two separate objects could not enumerate the items in the Stack concurrently, because there's no way of knowing who's calling the next method; the enumeration could not be restarted, because the Iterator interface doesn't have methods to support that; and the enumeration could be invoked only once, because the Iterator interface doesn't have methods for going back to the beginning. Instead, a helper class should do the work for Stack.
    The helper class must have access to the Stack's elements and also must be able to access them directly because the Stack's public interface supports only LIFO access. This is where inner classes come in.
    Here's a Stack implementation that defines a helper class, called StackIterator, for enumerating the stack's elements:
    public class Stack {
    private Object[] items;
    //code for Stack's methods and constructors
    not shown
    public Iterator iterator() {
    return new StackIterator();
    class StackIterator implements Iterator {
    int currentItem = items.size() - 1;
    public boolean hasNext() {
    public Object next() {
    public void remove() {
    or you can visit here
    http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html

    the context is about there is a class Stack, and this
    class want to implement some function of interface
    Iterator,but as the book said
    we should not let class Stack implement the Iterator
    directly, we should add a inner class inside the
    Stack .Simply because the implementation of the Iterator is nobody's business. By declaring it to be a private inner clss, nobody will ever know about it and only see the Iterator interface.

Maybe you are looking for