Clarification about inner class - why use it?

hi all
i just have a request to get some clarification on inner class. why do we use it and is it common to use it? thanks.

hi all
i just have a request to get some clarification on
inner class. why do we use it and is it common to use
it? thanks.It is realtively common. You may use one if you need to implement a class that's only relevant to one other class, like a data container or EventListener. Since it's probably interlocking tightlyx with its "outer" class, but doesn't need to be in reach of any other classes, its visibility can be confined to the outer class itself. Plus, objects from inner classes - if not declared static - are always tied to the existance of an outer class instance.

Similar Messages

  • Why method local inner class can use final variable rather than....

    Hi all
    Just a quick question.
    Why method-local inner class can access final variable defined in method only?
    I know the reason why it can not access instance variable in method.
    Just can not figure out why??
    any reply would be appreciated.
    Steven

    Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

  • Question about inner class - help please

    hi all
    i have a question about the inner class. i need to create some kind of object inside a process class. the reason for the creation of object is because i need to get some values from database and store them in an array:
    name, value, indexNum, flag
    i need to create an array of objects to hold those values and do some process in the process class. the object is only for the process class that contains it. i am not really certain how to create this inner class. i tried it with the following:
    public class process{
    class MyObject{}
    List l = new ArrayList();
    l.add(new MyObject(....));
    or should i create the object as static? what is the benifit of creating this way or static way? thanks for you help.

    for this case, i do need to create a new instance of
    this MyObject each time the process is running with a
    new message - xml. but i will be dealing with the case
    where i will need a static object to hold some
    property values for all the instances. so i suppose i
    will be using static inner class for that case.The two situations are not the same. You know the difference between instance variables and static variables, of course (although you make the usual sloppy error and call them static objects). But the meaning of "static" in the definition of an inner class is this: if you don't declare an inner class static, then an instance of that inner class must belong to an instance of its containing class. If you do declare the inner class static, then an instance of the inner class can exist on its own without any corresponding instance of the containing class. Obviously this has nothing to do with the meaning of "static" with respect to variables.

  • How to make an object of inner class and use it ?

    Hi tecs,
    In my JSF application i have a need to make an inner member class in one of my bean class.
    How can i make the object of this class?(what should be the entry in faces-config)
    And there are text box and check box (in the JSP) associated with the elements of this inner class. What should be the coding in JSP so that elements in the JSP can be linked with the corresponding members of the inner class ?
    Plz help.
    Thnx in advance.

    Hi
    I am havin 10 text boxes in my application.
    But out of 10 , 3 will be always together(existence of one is not possible without the other two.)
    Now i want to create a vector of objects ( here object will consist of the value corresponding to these three boxes),there can be many elements in this vector.
    So i m thinking to make an inner class which have three String variables corresponding to these text boxes that exists together.
    What can b done ?

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

  • Why Inner class cannot access static variables

    Why is it that inner class can use only static final variables of the outerclass, and not ordinary static variables of the outer class. "Yes the JLS sepcifies that only final static variables can be used inside an inner class, esp a non blank final variable". But why this restriction.
    Thanks.

    so what are final static variables treated as if they
    are not variables. So if the final static value is
    not loaded when the class is loaded how will the
    class know about the value.??The actual value wil be substituted for the name of a static final value at compile time. That's why you can use them in switch statements where you can't use any variable variable.
    This is something to watch out for, by the way, because if you use a public static final value from one class in another the actual value will be compiled into the using class, so if you change the value where it's defined the class using it will have the old value until it's recompiled.

  • Inner Classes - when to use with Swing?

    Hi again,
    I was creating a GUI with JTabbedPane as content pane, while doing the single panes in the different tabs i started wondering about some design issues.
    Let�s say you have a pane that is composed of 3 "subpanes" ( containing all the interaction components ). Should i write "normal" classes for each of the subpanes or is it more reasonable to define them as inner classes of the "main" panel - that�s at least what i thought because those 3 smaller panels are bound to the main panel for their lifetime...
    Any design tips about inner classes and swing or even inner classes in general, i�d really appreciate.
    Thx

    The concept of inner classes design in java is (I hope) they provide 'composite aggregation' relation with the contained class.
    Means that the (inner) class cannot exists alone and provide functionalities like other classes. Inner classes refer to the "contains" relationship in the UML.
    The other regular associations say, having a value oject model to an UI are Structural Aggregation, means that the value object can be used in the UI and also separately.
    For your case the inner classes are not suitable. You may have to find a suitable mechanism to get the individual tab panes. Probably use an interface to bridge the three tab panes and use an manager class, pass and id to the manager class and get the required Tabbed pane.
    Thanks,
    ananth
    Hi again,
    I was creating a GUI with JTabbedPane as content pane,
    while doing the single panes in the different tabs i
    started wondering about some design issues.
    Let�s say you have a pane that is composed of 3
    "subpanes" ( containing all the interaction components
    ). Should i write "normal" classes for each of the
    subpanes or is it more reasonable to define them as
    inner classes of the "main" panel - that�s at least
    what i thought because those 3 smaller panels are
    bound to the main panel for their lifetime...
    Any design tips about inner classes and swing or even
    inner classes in general, i�d really appreciate.
    Thx

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

  • A question about local inner classes

    Suppose an inner class created in a method:
    public void thisMethod(final int a){
                 class InnerClass {
                   //code
    }Why, in order to use the parameter a in the inner class, I have to pass it final?

    Aurelious wrote:
    JoachimSauer wrote:
    Because you can't refer to the argument of a method once the method call is completed (since the method argument lives on the stack).Why does that matter? If the parameter is of a primitive type, the object will get a copy of it anyway. If the parameter is not primitive, then the value on the stack will be a reference to the argument and not the argument-object itself. In either case, it should then be safe to modify the value after the method returns, as it will either be the primitive copy or a copy of a reference to the object which is itself not on the stack, so the field referenced by the object is still valid either way.
    Am I missing something?If your inner class is using a local variable in the calling method, the expectation is that it's the same variable. But it's not. If it were, then when the stack frame was popped, the variable would be out of scope, which is incompatible with the fact that the inner object can live on.
    On the other hand, if we copy it without making it final, then that's misleading. It looks like I have the same variable, but if I change it in the method, it doesn't change in the object, and vice versa.
    So we have to make a copy to prevent scope/lifetime problems, and we have to make it final so that the copy can be indistinguishable from it being the same variable.

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

  • Crazy inner class question

    Write a java file and compile it. The compiled class size is X. Add an inner class and the size increases as well as adding another class file.
    Decompile both.
    You will see that the entire inner class is defined in the outer class as well as being in it's own class. Why is this necessary? Since you reference an inner class by using the outer class name, why do you need to have a separate inner class.class file generated?
    Thanks
    ST

    You will see that the entire inner class is defined in
    the outer class as well as being in it's own class.No, that is not true. The inner class is defined only in a separate class file.
    Why is this necessary? Since you reference an inner
    class by using the outer class name, why do you need
    to have a separate inner class.class file generated?Because inner classes was an addition to the Java language that the JVM does not know about. Therefore inner classes are translated into ordinary classes by the compiler.

  • Need Help in Inner Classes

    Hi
    I joined as a faculty last week in an institution. To take class I need some information about inner classes in java.
    Basically i need where we use this concept in real time application. Now it is used by the developer or not? Moreover how it is working in java?
    Please somebody help me out...
    thanks in advance
    Chithrakumar

    I once wrote the following example class showing a bit of inner classes"public class Star {
         private String name;
         public Star(String name) { this.name= name; }
         public class Planet {
              private String name;
              public Planet(String name) { this.name= name; }
              public class Moon {
                   private String name;
                   public Moon(String name) { this.name= name; }
                   public String toString() { return name+" (orbiting "+Planet.this+")"; }
              public String toString() { return name+" (orbiting "+Star.this+")"; }
         public String toString() { return name; }
         public static void main(String[] args) {
              System.out.println(new Star("sun").new Planet("earth").new Moon("moon"));
    }Study it, run it and see if you understand what this is all about.
    kind regards,
    Jos

  • Another exception... Serializing inner classes

    Basically, I am tesing class dynamic loading, which I am failing to do till now using codebase within the local system. This was my original question,,, you can see it here http://forum.java.sun.com/thread.jspa?threadID=581979&tstart=0
    which I did not solve as of yet.
    However, this is a new question:
    Does this error look nice? am I making a mistake when serializing and returning an object of an inner class by a remote call?? I have this code in the server class:
    public Message getMessage()throws RemoteException{
    return new MyMessage();
    private class MyMessage implements Message{
    //code
    }Clinet class:
    Message message=server.getMessage(); //generates ExceptionException :
    java.lang.ClassCastException: cannot assign instance of $Proxy0 to field Server$MyMessage.this$0 of type Server in instance of Server$MyMessage
         at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:1977)
         at java.io.ObjectStreamClass.setObjFieldValues(ObjectStreamClass.java:1157)
         at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1918)
         at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1836)
         at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1713)
         at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1299)
         at java.io.ObjectInputStream.readObject(ObjectInputStream.java:339)
         at sun.rmi.server.UnicastRef.unmarshalValue(UnicastRef.java:290)
         at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:139)
         at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:179)
         at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132)
         at $Proxy0.getMessage(Unknown Source)
         at Client.main(Client.java:30)
    thank you very much...

    I believe I need to have a better design as you are
    suggesting...
    I want to have a set of Remote interfaces that can be
    implemented by different ways. These interfaces are
    then distributed for other developpers. Assuming it
    is a chat program where clients send Messages to
    other clients through a server, I would like to have
    each client implement his own RemoteClient in a way
    that suits him using Callbacks. Serializing a class
    that implements Message can be used to have it as
    means to communicate. Dynamic class loading is then
    used to get the classes for different implementation
    of Message that circles the clients.
    Two pieces definitely. The message which is of the group that says "please do this" and the functional part which is "for a given message do this".
    There are probably other parts as well.
    In that form, I wanted to test serializing anonymous
    Messages, but it did not work because the enclosing
    class will also be serialized (if it implemented
    Serializable of course) or would throw an exception
    if it does not implement it like the one in the
    questions above as I have learned. Even if Inner
    classes are used it still will not work. Only normal
    classes, or static inner classes would work.
    If the "functionality" is truly general then there probably should be only one message. It would have attributes something like this...
    - Function request name
    - List of function parameters.
    - List of function results.
    After getting answers to my problems, as always, I
    end up meeting new problems, I have these questions:
    How to serialize Actions(AbstractActions,
    ActionListeners)??What is an "action" and why do you need to serialize it?
    If it is a message then make it a message.
    How can I serialize this:
    button.addActionListener(new ActionListiner(){
    public void actionPerformed(ActionEvent e){You don't. At least not in terms of your above problem description.
    This code is gui code. It is neither a message nor a "function". You don't send guis somewhere else.
    /// or this
    button.addActionListiner(new MyAction());
    static class MyActionExtends implements
    ActionListener{
    public void actionPerformed(ActionEvent e){
    //code
    }Again you don't. I suspect you are mixing functionality.
    Your gui should talk to your message layer. You might even have a gui layer, a message layer and a message-gui layer.
    How can I overcome this problem?? Sending a GUI
    through RMI looks very nice!!! with Buttons that
    perform Remote Actions!!
    Based on your system description above it is simply wrong.
    Maybe there is more to your system though.

  • Inner class vs. imported class

    Hi everyone,
    I have entitiy beans created for a client's web app I'd like to use in the
    web service using WebLogic Workshop 7.0. Say the classes are imported like
    this in the services:
    import com.hoike.clientname.ap.bean.Invoice
    import com.hoike.clientname.ap.bean.Vendor
    Instances of these classes are used in callback methods and some of the
    service methods.
    When I generate the CTRL file, it actually adds those imported classes as
    inner class of the service defined.
    The problem is that when I try to used these services from another service,
    I cannot use the imported classes (as Invoice or Vendor), but instead I have
    to use the inner class (InvoiceService.Invoice or VendorService.Vendor)
    Does WebLogic Workshop 7.0 only allow you to use inner classes? Is there a
    way to use custom classes as method parameters?
    Thanks in advance!
    Makoto

    how do you declare your inner class?
    Is it (public)
    public static class MyInnerClassor (private)
    private static class MyInnerClassor (package)
    static class MyInnerClassor (protected)
    protected static class MyInnerClassTry to change the way you declare the inner class. Use protected or package or public instead.

  • HELP: Inner Class vs. Private Member

    I use "javadoc -private" to create documents with inner classes. As a result, all private fields and methods, which I don't need, show up in the same document. Is there any way I can have inner classes without private members?

    how do you declare your inner class?
    Is it (public)
    public static class MyInnerClassor (private)
    private static class MyInnerClassor (package)
    static class MyInnerClassor (protected)
    protected static class MyInnerClassTry to change the way you declare the inner class. Use protected or package or public instead.

Maybe you are looking for