Why do we go for inner classes in java?

why cant we inherit the classes instead of having inner classes.
what is the exact difference between the inner class and subclass.
can anyone please explain me with some examples

An inner class doesn't have any relationship with the outer class per se,
except for one thing: an instantiation of the inner class can refer to the
members of the instantiation of the outer class. One instantiation of the
outer class can have many instantiations of the inner class 'circling
around' it. Try to implement the following example using inheritance:public class Star {
     private String name;
     public Star(String name) { this.name= name; }
     public Planet addPlanet(String name) { return new Planet(name); }
     public class Planet {
          private String name;
          private Planet(String name) { this.name= name; }
          public Moon addMoon(String name) { return new Moon(name); }
          public class Moon {
               private String name;
               private Moon(String name) { this.name= name; }
               public String toString() { return name+" (circling around "+Planet.this+")"; }
          public String toString() { return name+" (circling around "+Star.this+")"; }
     public String toString() { return name; }
     public static void main(String[] args) {
          System.out.println(new Star("sun").addPlanet("earth").addMoon("moon"));
}kind regards,
Jos

Similar Messages

  • Why and how to use "inner class"

    When i am learning advanced java language features,
    i could not understand why and when to use the "inner class",
    who can give me some examples?
    Thanks!

    You would use an inner class when an object needs visibility of the outer class. This is akin to a C++ friend.
    An example of this is an iterator. An iterator over some collection is typically implemented as an inner class of the collection class. The API user asks for an Iterator (from the Collection) and gets one - in fact they receive an instance of an inner class, but doesn't care. The iterator needs to be inner, as the iterator needs to see the internal data structures of the outer (collection) class.
    This could also be done with an anonymous class, as mentioned by spenhoet above. However, in the case of a collection, the role of the iterator is clear - thus it deserves its own class. And often there is more than one place an iterator can be returned (e.g. see java.util.List, which has several methods that return Iterators/ListIterators), thus it must be put in its own class to allow reuse of the code by outer class.

  • Examples For 4 types of Inner Classes in java..

    Hi all,
    It would be gr8 help if u poeple provide me some examples in Java APIs for 4 types of Inner Classes.
    Normal Inner Class,Static Inner Class,Method Local Inner Class and Anonymous Inner Class.
    Thank you ..

    bprathibha wrote:
    ok... not to read..
    I was asked this question in an interview.
    I was unable to answer this question.I guess you know how to write a class?
    Normal Inner Class,Static Inner Class,Method Local Inner Class and Anonymous Inner Class.A normal inner class is a class that is written inside another class. A static inner class is the same thing as the normal inner class except that it's declared to be static. A method local class is a class that is declared within a method and it's only known within that method. An anonymous class is where you create a subclass and instantiate it at the same time. The construction if often used in UI programming. E.g.
    public void addListeners() {
        button.addActionListener(new ActionListener() { //Anonymous class
            public void actionPerformed(ActionEvent e) {
    }Kaj

  • Java Decompiler for Inner classes

    Hi,
    I am looking for a Java Decompiler that can handle the decompiling of inner classes fairly well. Any help will be appreciated. Thanks.

    dj decomplier is probably the best one. u can look for it on google.

  • Calling functions of the inner class in .java code file

    Hello,
    I created a .java code file in Visual J#.Net and converted it into
    the application by adding the "public static void main(String args[])"
    function.
    I have created the two classes one extends from Applet, and the other
    extends from Frame. The class which I inherited from the Frame class becomes
    the inner class of the class extended from the Applet. Now How do I
    call the functions of the class extended from Frame class - MenuBarFrame
    class. the outline code is
    public class menu_show extends Applet
    ------init , paint action function---------
    public class MenuBarFrame extends Frame
    paint,action function for Menu
    public static void main(String args[])
    applet class instance is created
    instance of frame is created
    Menu , MenuBar, MenuItem instance is created
    and all these objects added
    I have Created MenuBarFrame class instance as
    Object x= new menu_show().new MenuBarFrame
    ????? How to call the functions such as action of MenuBarFrame class - what
    should be its parameters??????
    }

    Here's how I would do it:
    interface Operation {
        public int op(int y);
    class X {
        private int x;
        public X(int x) {
            this.x = x;
        private class Y implements Operation {
            public int op(int y) {
                return x+y;
        public Operation createOperation() {
            return new Y();
        public static void main(String[] args) {
            X app = new X(17);
            Operation f = app.createOperation();
            System.out.println(f.op(-11));
    }Your code, however, has some serious "issues". You typically don't
    instantiate an applet class -- that's the job of the applet viewer or Java plugin
    your browser is using. If you instantiate the applet directly, you're going
    to have to supply it an AppletStub. Do you really want to go that way?
    Again, use an applet viewer or browser, or better yet, why write applets at all?

  • Class not Found Execption for inner classes

    Hi ,
    When I am trying to deploy a custom component despite of putting the class path I am facing isses regarding class not found for classes that are present in an inner jar.Can someone please let me know what could nbe wrong.Please let me know the correct way of doing so.
    I am adding a data type as well and adding the path thre also.
    Regards,
    Leena

    The most common problem is in the path part of the class-path.  One thing to remember is not to bother with .. or / at the start of the path.  For example my jar files are in a lib folder off the root of my application:
    <class-path>lib\aglj40.jar lib\pdfcore.jar lib\pdfencryption.jar lib\pdfservices.jar lib\rideau.jar</class-path>

  • Tool for Reversing (.class to .java classes)

    Can somebody tell me about an open soft tool for reverting code.
    Thanks.
    FS

    java decompiler. Try google. There are dozens of them.

  • Why have inner classes

    Well I can understand the purpose of inner classes in multithreaded applications or where you need a continous monitoring, but I have always been wondering why use an inner application in a normal application. Any ideas?

    I guess you mean "inner class in a normal applications" in the last line of your question? If not, don't mention reading this reply since it doesn't answer your question in the latter case.
    Otherwise, the most common use for inner classes according to me is event handling and out of pure lazyness. Good programmers should be lazy you know.
    Let me give an example:
    public class Test() extends Applet{
    <some code here>
    private class Handler extends MouseAdapter(){
    public void mouseEntered(MouseEvent evt){
    <some event handling>
    In the example above we have an applet in which we want to do some MouseEvent handling.
    You could implement the mouselistener in your applet or you could create an inner class that extends MouseAdapter.
    When you implement the MouseListener interface, you have to define all methods from this interface in your applet to prevent it from being abstract.
    When you use an innerclass you only have to provide the method which you want to override, all the other are already implemented by extends the adapter.
    Another advantage of innerclasses is that you have access to all classvariables of the class in which you defined your inner class.
    I hope this can be a little help for you.

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

  • Extending a member inner class

    I have a class
    public class A{
    class InnerClassB{
    Now the question is how to extend the inner class would it be
    class ExtendingInnerClassB extends A.B{
    or else?
    I am not sure anybody knows?

    Regarding inheritance from inner classes you must define your constructor:
    public ExtendedInnerClass(EnclosingClass EC) { EC.super(); }
    why?????
    well
    1. Where is the handle? The handle is an internal thing which is designed to accept the enclosing class. It is something which is not in the programmer's control. when there is an inner class, it is natural that the inner class cannot exist without its outer class. And that is the reason why the instantiation of an inner class is done using new OuterClass().new Innerclass(). U can see that the innerClass object is created based on the outer class object (assuming that the inner Class is not static). I hope that this is clear. Now .. the whole point is how does the compiler know that the Outerclass is the enclosing class? When the above line is compiled, the tricky handle in the inner class is assigned to the Outer class. So any reference henceforth is made based on this handle.
    2. In the Inherited Inner class, there is no way to assoicate the handle in the above manner. Hence we are forcing by calling the super().
    3 Otherwise why not simply create with: new InheritedInnerClass(EnclosingClass)? This is not possible. What if the inherited inner class needs a constructor in the above manner. That is assume that there is a class A. Then if the Inner Class needs the constructor to be InnerClass(A a, EnclosingClass b) for some other purpose, then what judgement can the compiler take? So that answers the question <b>Can't the compiler compile the inherited inner class assuming a handle to the enclosing class and then force an instance to be created using the EnclosingClass.new syntax?</b> Becuase in this case it cant go by any assumption.
    4. Maybe the compiler designers can make some change such that the inherited inner class should have all its constructors beginning with the enclosing object and there should be atleast one constructor. But somehow I feel that it is too much of asking.

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

  • Problems with inner classes

    I ran into the following problems when I tried to read into an inner class:
    This is my .jdo file
    <?xml version="1.0"?>
    <jdo>
    <package name="com.globalrefund.jdo.mna">
    <class name="Parameter$Syspar" objectid-class="SysparId">
    <extension vendor-name="kodo" key="table" value="syspar"/>
    <extension vendor-name="kodo" key="lock-column" value="none"/>
    <extension vendor-name="kodo" key="class-column" value="none"/>
    <field name="landescode" primary-key="true">
    <extension vendor-name="kodo" key="data-column"
    value="landescode"/>
    </field>
    <field name="waehrungscode">
    <extension vendor-name="kodo" key="data-column"
    value="waehrungscode"/>
    </field>
    </class>
    </package>
    </jdo>
    1.) appidtool does not work for this inner class, I get this stack trace
    C:\users\Bernhard\jbProject\refundManual>appidtool
    src\com\globalrefund\jdo\mna\Parameter$Syspar.jdo
    Generating an application id for type "class
    com.globalrefund.jdo.mna.Parameter$Syspar"...
    Exception in thread "main" java.lang.NullPointerException
    at com.solarmetric.kodo.enhance.ApplicationIdTool.getFile(Unknown
    Source)
    at
    com.solarmetric.kodo.enhance.ApplicationIdTool.writeApplicationId(Unknown
    Source)
    at
    com.solarmetric.kodo.enhance.ApplicationIdTool.writeApplicationId(Unknown
    Source)
    at com.solarmetric.kodo.enhance.ApplicationIdTool.main(Unknown
    Source)
    2.) I tried to use a hand coded inner class as ID class, but id did not work
    (is this not possible ?)
    Exception in thread "main" java.lang.NoSuchMethodError:
    com.globalrefund.jdo.mna.Parameter$SysparId: method <init>()V not found
    at
    com.globalrefund.jdo.mna.Parameter$Syspar.jdoNewObjectIdInstance(Parameter.j
    ava)
    at
    javax.jdo.spi.JDOImplHelper.newObjectIdInstance(JDOImplHelper.java:166)
    at com.solarmetric.kodo.util.ObjectIds.fromPKValues(Unknown Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.createFromResultSet(
    Unknown Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager$2.getResultObject(Un
    known Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.instantiateRow(Unknown
    Source)
    at com.solarmetric.kodo.impl.jdbc.runtime.LazyResultList.get(Unknown
    Source)
    at java.util.AbstractList$Itr.next(AbstractList.java:416)
    at com.solarmetric.kodo.runtime.ResultListIterator.next(Unknown
    Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.ResultListFactory.createResultList(Un
    known Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCStoreManager.executeQuery(Unknown
    Source)
    at
    com.solarmetric.kodo.impl.jdbc.runtime.JDBCQuery.executeQuery(Unknown
    Source)
    at com.solarmetric.kodo.query.QueryImpl.executeWithMap(Unknown
    Source)
    at com.solarmetric.kodo.query.QueryImpl.execute(Unknown Source)
    at
    com.solarmetric.kodo.query.QueryImpl$SynchronizedQuery.execute(Unknown
    Source)
    at com.globalrefund.jdo.mna.Parameter.<init>(Parameter.java:71)
    3.) It worked after I moved the ID class into a separate class
    Regards,
    Bernhard

    1.) appidtool does not work for this inner class, I get this stack traceThis is a bug. It will be corrected in the final release of 2.3, due out
    Real Soon Now. Thanks for catching this!
    2.) I tried to use a hand coded inner class as ID class, but id did not work
    (is this not possible ?)
    Exception in thread "main" java.lang.NoSuchMethodError:
    com.globalrefund.jdo.mna.Parameter$SysparId: method <init>()V not foundThis exception is saying that your application ID class does not have a
    no-args constructor. Make sure the id class is a static inner class;
    otherwise Java transparently adds a parent object parameter to each
    constructor, and so the application id class will violoate the JDO constraint
    of having a no-args constructor.

  • Problems with inner classes in JasminXT

    I hava problems with inner classes in JasminXT.
    I wrote:
    ;This is outer class
    .source Outer.j
    .class Outer
    .super SomeSuperClass
    .method public createrInnerClass()V
         .limit stack 10
         .limit locals 10
         ;create a Inner object
         new Outer$Inner
         dup
         invokenonvirtual Outer$Inner/<init>(LOuter;)V
         ;test function must print a Outer class name
         invokevirtual Outer$Inner/testFunction ()V
    .end method
    ;This is inner class
    .source Outer$Inner.j
    .class Outer$Inner
    .super java/lang/Object
    .field final this$0 LOuter;
    ;contructor
    .method pubilc <init>(LOuter;)V
         .limit stack 10
         .limit locals 10
         aload_0
         invokenonvirtual Object/<init>()V
         aload_0
         aload_1
         putfield Inner$Outer/this$0 LOuter;
         return
    .end method
    ;test
    .method public testFunction ()V
         .limit stack 10
         .limit locals 10
         ;get out object
         getstatic java/io/PrintStream/out  java/io/PrintStream;
         aload_0
         invokevirtual java/lang/Object/getClass()java/lang/Class;
         ;now in stack Outer$Inner class
         invokevirtual java/Class/getDeclaringClass()java/lang/Class;
         ;but now in stack null
         invokevirtual java/io/PrintStream/print (Ljava/lang/Object;)V
    .end methodI used dejasmin. Code was equal.
    What I have to do? Why getDeclatingClass () returns null, but in dejasmin code
    it returns Outer class?

    Outer$Inner naming convention is not used by JVM to get declaring class.
    You need to have proper InnerClasses attribute (refer to http://java.sun.com/docs/books/vmspec/2nd-edition/html/ClassFile.doc.html#79996)
    in the generated classes. Did you check using jclasslib or another class file viewer and verified that your .class files have proper InnerClasses attribute?

  • 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");

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

Maybe you are looking for