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.

Similar Messages

  • Design question about when to use inner classes for models

    This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
    The tutorial I'm following in particular is this one:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.

    It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
    quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
    Man adding a button to a table is much more difficult than I imagined.
    Message was edited by:
    deadseasquirrels

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

  • When will we use inner class

    hi
    when will we use inner class?

    JosAH basically already wrote this, but another way
    to say the same thing is this. If you are writing a
    class and you find it would be handy to have another
    class for that class to use, you can either write a
    separate class for each, or you can embed one in the
    other, making it an inner class. One advantage of an
    inner class is that you can meet a set of
    specifications by not having an extra class. It also
    makes more sense to have an inner class if it's
    something that's not useful on its own.I think it is the second most important advantage of inner class
    (First is: you can access the private members of the outer class)

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

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

  • Help! - JRE can't find classes that use inner classes!

    Whenever I try to launch an app using the JRE, if the class was built with an inner class definition, the JRE says it can't find the class.
    For instance:
    I created a class called GUI, which contains anonymous inner class definitions for the button handlers: addActionListener(new ActionListener()){, etc. 
    When I compile this class I get GUI.class and GUI$1.class
    When I try to launch this using the JRE:
    jre -cp c:\progra~1\myApps GUI
    The JRE spits out
    'Class not found: GUI'
    BUT if I go back and remove the action handlers so that the only compiled class file is GUI.class (not GUI$1.class) then the JRE can find the class no problem.
    What in the good Lord's name is going on here?

    Thanks for the response. Got the 1.2.2 version of the JRE, where I guess you no longer invoke jre.exe (no such file exists) but java.exe instead (not well documented).
    Also, the newer version of the JRE has no problems locating classes, so I guess I'm OK.

  • Why can't inner classes have static methods?

    I just tried to add a static method to an inner class, which would have been useful for extracting constants about said inner class, and it turns out that is not allowed.
    Of course I have other ways to code what I wanted, but I'm curious as to why this restriction was set in place. Anybody know?

    Probably because an inner class is tied to an instance of the enclosing class. I think that, conceptually at least, the inner class' definition itself only exists in the context of an instance of the enclosing class. While I'm sure it would have been technically possible to allow it, it would be confusing and not make a whole lot of sense--what is the static context for the inner class, since the class only exists in a non-static context?

  • How to use inner class in axis2 in java?

    Hi,
    Iam very new in axis2. My language is java. What iam trying to do is, i need to create a xml format for the clients to send data to server using axis2 service.
    My demo xml format is,
    <test1>
    <test2>
    <test3>
    <test4></test4>
    <test5></test5>
    </test3>
    <test3>
    <test4></test4>
    <test5></test5>
    </test3>
    </test2>
    </test1>
    Iam trying to use nested inner class to generate this xml. Below is my demo java class. But unfortunately, or may be lac of knowledge, iam unable to create sub trees.
    public class EchoService{
    public MyInnerClass retMyInnerClass(MyInnerClass test1) {
    return test1;
    public class MyInnerClass {
    private String test2;
    public MyInnerClass() { }
    public void setTest2(String test2) {
    this.test2 = test2;
    public String getTest2() {
    return this.test2;
    Please help me to generate the web service for client.
    Thanks in advance.

    847897 wrote:
    well, i apologies for that fault. But i need the answer. It is urgent.That's your problem, not ours. However, I don't see the connection between your inner class and producing XML subtrees. Perhaps if you explained the problem, rather than your solution...
    [url http://sscce.org/]This page is usually a good place to start; otherwise [url http://www.catb.org/~esr/faqs/smart-questions.html]this one.
    Winston

  • My canon t3i dslr camera automatically stops recording after about 10 sec. using a class 10 card.

    Hello,
    My canon t3i dslr camera stops recording automatically after about 10 sec. the manual said to use an SD card of class 6 or higher. I am using a class 10 and I have been able to record long videos in the past and all of a sudden the camera stops recording automatically after about 10 sec. Does anyone know why?  thanks

    Hi Rockinruby.
    We get this a lot here.  It turns out that even though the card is labeled as a Class 10 card, the most common problem when this occurs... is that it's still a defective card.
    Sandisk is a good company and they generally make solid products.  But there are two risks... (1) even Sandisk will occasionally have a bad card or a card that fails prematurely, and (2) it's exceptionally easy to create a forgery (if you peel the labels off these cards, they all look identical.)  
    When I buy cards (and I also buy Sandisk and/or Lexar cards), I'm careful to buy cards which well-exceed the specs necessary ... but I'm also careful to buy the cards only from reputable dealers.
    If you do a search, you'll find LOTS of articles about fake cards with tips on how to avoid them or how to spot them.
    But the bottom line ... at the end of the day you just want your problem solved.  If the card is bad, then there's nothing that you  would be able to do to the camera to make the problem away.  You would really need to replace that card.
    The issue that you are having is somewhat common... there are lots of threads on this.  But the majority of these are actually solved simply by replacing the card with a known good card and without making any changes to the camera.  
    It's not a guarantee that it's the card... but it's the most common cause.
    Tim Campbell
    5D II, 5D III, 60Da

  • Why to use wrapper class?

    hello,
    can anybody please tell me why wrapper class are used in JAVA and what are exactly wrapper class?
    reply me soon....

    I want to give an example and then explain why it is for. Primitives will be good example for this situation.
    Example:
    Below are the primitive types and their wrapper classes...
    Primitive to Wrapper Class
    byte - Byte
    short - Short
    int - Integer
    long - Long
    char - Character
    float - Float
    double - Double
    boolean - Boolean
    USING OBJECT CREATION
    Think a situation when you create an integer object using this code:
    ---> Integer intVar = new Integer();
    you have the methods and constants:
    1 MAX_VALUE ,
    2 MIN_VALUE ,
    3 byteValue() ,
    4 compareTo(Integer anotherInteger) ,
    5 compareTo(Object o) ,
    6 decode(String nm) ,
    7 doubleValue() ,
    8 equals(Object obj) ,
    9 floatValue() ,
    10 getInteger(String nm) ,
    11 getInteger(String nm, int val) ,
    12 getInteger(String nm, Integer val) ,
    13 hashCode() ,
    14 intValue() ,
    15 longValue() ,
    16 parseInt(String s) ,
    17 parseInt(String s, int radix) ,
    18 shortValue() ,
    19 toBinaryString(int i) ,
    20 toHexString(int i) ,
    21 toOctalString(int i) ,
    22 toString(),
    23 toString(int i) ,
    24 toString(int i, int radix) ,
    25 valueOf(String s) ,
    26 valueOf(String s, int radix)
    now you have an object with 2 constants and 24 methods.
    USING WRAPPER CLASS
    and think using wrapper class of Integer..
    CODE ---> int intVar = Integer.parseInt((String)someStringData);
    In this case your Integer object have the methods and constants
    1 MAX_VALUE ,
    2 MIN_VALUE ,
    3 parseInt(String s) ,
    4 parseInt(String s, int radix) ,
    5 toBinaryString(int i) ,
    6 toHexString(int i) ,
    7 toOctalString(int i) ,
    8 toString(int i) ,
    9 toString(int i, int radix) ,
    10 valueOf(String s) ,
    11 valueOf(String s, int radix)
    as you in this situation you have 2 constants and 9 methods.
    AS YOU SEE THERE ARE 15 METHODS DIFFERENCE FROM THE OBJECT AND THE WRAPPER CLASS OF INTEGER OBJECT.
    NOW TALKING ABOUT PRIMITIVE TYPES ALL PROGRAMMERS USED THIS TYPES FOR THEIR CODES AND THEY ALWAYS NEED SOME THIS KIND OF CASTING. IN MY EXAMPLE I TAKE THE VALUE OF AN STRING VARIABLE. AND THERE ARE LOTS OF THINGS SIMILIAR TO THIS EXAMPLE.
    IDEA OF THIS WRAPPER CLASSES IS THAT USE AS YOU NEED NOTHING MORE. IN THE WRAPPER CLASS YOU DONT HAVE INTEGER OBJECT. YOU ONLY NEED THE PARSEINT METHOD OF INTEGER OBJECT INSTEAD OF CREATING THE INTEGER OBJECT YOU USE THE WRAPPER CLASS OF THIS TYPE...
    OBJECTS ARE STORED IN A MEMORY PLACE CALLED HEAP WHICH IS PLACED ON RAM AND GARBAGING OF THIS OBJECTS TAKES MORE TIME TO ALLOCATE FROM HEAP STORAGE.
    AND ANOTHER NOTE FOR THIS WRAPPER CLASSES if you want to store an int inside a container such as an ArrayList (which takes only Object references), you can wrap your int inside the standard library Integer class
    EX:
    import java.util.*;
    public class ImmutableInteger {
    public static void main(String[] args) {
    List v = new ArrayList();
    for(int i = 0; i < 10; i++)
    v.add(new Integer(i));
    // But how do you change the int inside the Integer?
    } ///:~
    GOOD LUCK...
    REALKINGTA....

  • Need help about ref cursor using like table

    Hi Guys...
    I am devloping package function And i need help about cursor
    One of my function return sys_refcursor. And the return cursor need to be
    join another table in database . I don't have to fetch all rows in cursor
    All i need to join ref cursor and another table in sql clause
    like below
    select a.aa , b.cc form ( ref_cursor ) A, table B
    where A.dd = B.dd
    I appeciate it in advance

    My understanding is that you have a function that returns a refcursor and is called by a java app.
    Because this is a commonly used bit of code, you also want to reuse this cursor in other bits of sql and so you want to include it like table in a bit of sql and join that refcursor to other tables.
    It's not as easy as you might hope but you can probably achieve this with pipelined functions.
    Is it a direction that code should be going down? yes, eventually. I like the idea of pulling commonly used bits of code into a SQL statement especially into the WITH section, provided it could be used efficiently by the CBO.
    Is it worth the effort given what you have to do currently to implement it? possibly not.
    what else could you do? construct the sql statement independently of the thing that used it and reuse that sql statement rather than the refcursor it returns?
    Message was edited by:
    dombrooks

  • Use inner class as collection

    Is there a way to get toplink to use an inner class collection to house my 1:m relationship. The collection needs some attributes of the containing object.
    Can i override how collection is constructed within the java, because it seems pretty clear the workbench doesn't support this.
    thanks
    craig

    Seem like an odd thing to do. If it were a static inner class it would be possible, but an instance inner class is probably not.
    If you really need a reference to the source object from the collection object, it might be better to accomplish this through making the inner collection class an outer class, or at least static. You could then set a back reference to the source object in the source object's set method for the collection. You would need to configure the mapping to use method access, or if using value holders you could lazily set the collection back reference from your get method for the collection. You could also make special get/set methods for TopLink to use to access the collection value that convert the special collect to and from a normal collection.
    In general it might be better to put the logic specific to the owning class in the owning class instead of the collection.

  • Help about dns error using linksys

    please help me. i'm using cable modem and linksys WRT54G. if I connect my cablemodem to linksys, I cant browsing to some website (e.g www.schroders.com.hk). but if i connect cable modem directly to my laptop, I can browse that website. please help me to solve this problem, thanks

    try reducing the MTU size on the router to 1400 and then 1300 .... trigger port 443 .. if nothing works , try upgrading / reflashing the firmware .. after the upgrade , reset and reconfigure the router ..

  • Need help about method close() in BufferedWriter Class

    Hi All,
    I'm a newbie in Java programming and I have problem regarding BufferedWriter class. I put the code snippet below.
    Sometimes I found wr.close() need a long time to be executed, around 9 seconds. For the normal case, it only needs 1 second. The transaction is same with the normal case and I found no errors in the log.
    Do you guys have any idea about this problem? What cases that can cause this problem?
    Thanks
    // Create a socket to the host
    InetAddress addr = InetAddress.getByName(shost);
    Socket socket = new Socket(shost, sport);
    // Send header
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
    data = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><request><contentcode>" + content_code +"</contentcode><msisdn>"+ orig_num +"</msisdn></request>";
    System.out.println("------------POST----------");
    wr.write("POST /" + surlname +" HTTP/1.1\r\n");
    wr.write("Host: " + shost + "\r\n");
    wr.write("Connection: close \r\n");
    wr.write("Content-type: text/xml \r\n");
    wr.write("Content-length: " + data.length() + "\r\n");
    wr.write("\r\n");
    wr.write(data);
    System.out.println("POST /" + surlname +" HTTP/1.1\r\n");
    System.out.println("Host: " + shost);
    System.out.println("Connection: close");
    System.out.println("Content-type: text/xml");
    System.out.println("Content-length: " + data.length());
    System.out.println("-------------------------");
    System.out.println("data = " + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><request><contentcode>" + content_code +"</contentcode><msisdn>"+ orig_num +"</msisdn></request>");
    wr.flush();
    // Get response
    BufferedReader rd = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    while ((linelength = rd.read(charline)) >0) {
    reply += new String(charline, 0, linelength);
    wr.close();
    rd.close();
    System.out.println("reply = " + reply);
    log.info("(New Log) reply = " + reply);

    sabre150 wrote:
    So what makes you think that not using StringBuffer is the cause of the OP's problem?Just by experience. The main cause of resource hogs in Java is large string concatenation enclosed in a loop.
    I've just made the following experience :
    public class Test {
        public static void main(String[] args) {
            new Test().execute();
        private void execute() {
            long a, b, c;
            String value = "A123456789B123456789C123456789D123456789";
            String reply = "";
            StringBuffer buffer = new StringBuffer();
            a = System.currentTimeMillis();
            for (int i = 0; i < 5000; i++) { reply += value; }
            b = System.currentTimeMillis();
            for (int i = 0; i < 5000; i++) { buffer.append(value); }
            reply = buffer.toString();
            c = System.currentTimeMillis();
            System.out.println("Duration - concatenation = " + (b-a) + " / string buffer = " + (c-b));
    }Output :
    Duration - concatenation = 21295 / string buffer = 7

Maybe you are looking for

  • How do I change the color of the triangle in a menu bar?

    Hi, I have a question that might seem very rudimentary...How can I change the color of the little downward-pointing triangle on my menu bar items that have sub-menus? Specifically, I want those triangles to be invisible when the cursor is not over th

  • Mismatched ABAP and JAVA SP Stacks

    Hi, We have upgraded to BI7 and are on SP Stack 14. We want to use our existing portal to implement BI-JAVA. However our portal is currently at SP13... We plan to align the stacks at the next patching exercise, but until then would it be better to de

  • Loading an AS2 swf into a AS3 project?

    I have an AS2 swf that is merely an image gallery made with a few components. I tried loading this swf into an AS3 project I am working on and it seems to load in and play properly in my AS3 file. I'm not looking to communicate with the AS2 swf with

  • Problems with deploying ODAC to web server

    I have a ASP.NET 4.0 MVC application using Entity Framework and ODAC r4 11.2.0.3.0. I have Oracle 10g client installed on the server (2003) already. I installed the 32-bit ODAC 4 XCopy deployment to the server using the batch file. So I have two Orac

  • Call child package x number of times from parent package

    I have a child package that I need to call x (10 or less) number of times and have those all run at the same time. The parent package should kick them off either simultaneously or one after the other, but the parent package should not complete until