This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
Private is only used when you're creating an inner class that you want to be only accessible within the class in which it is declared. From the JLS, §8.1.1 Class Modifiers:
The access modifiers protected and private pertain only to member classes within a directly enclosing class declaration...
So, how about an example. You could potentially implement an Iterator this way...
Notice that the StringListIterator class is a separate class from StringList, but it really has no meaning outside of the StringList class - it is essentially tied to the implementation of StringList. Therefore, a private inner class works very nicely to encapsulate that functionality. I hope that helps, Corey
but is it allowed to return a private class object from a public method of outer class(as above code giving new object of StringListIterator) that means u can modify the StringListIterator data from outside?? thnx rishi [ August 14, 2003: Message edited by: Rishi Wright ]
No it is not possible as the StringIterator class is essentially a private variable in the out class...therefore only instances of the outer class can use (and therefore modify) instances of the StringIterator Regards, /Niall
Joined: Jul 22, 2003
Originally posted by Niall ORiordan: No it is not possible as the StringIterator class is essentially a private variable in the outer class...therefore only instances of the outer class can use (and therefore modify) instances of the StringIterator Regards, /Niall
Joined: Dec 20, 2001
What I've done here is really no different from a normal getter/setter. Take this example:
In this case, some external class could invoke getL() to get a reference to the private object l and then do whatever it wants with it. In my example, I've really done the same thing. Note, however, that you're still "in control" of how the user interacts with that object. We haven't made the StringListIterator class public so the only way it can be access (as I have it written) is to invoke the StringList.iterator() method. Now, once the external class has a reference to that StringListIterator object, it is free to do whatever the StringListIterator class allows. However, it only allows the user to invoke 3 public methods. What I've done in the Iterator example really isn't very different from the example I just showed here. The only difference is that, in my first example, the StringListIterator class was definied within the StringList class. In the second example, the ArrayList class is defined in some other file. I hope that helps, Corey
Joined: Jun 25, 2003
Thanks Corey...I got it ..I forgot that private inner class is just like any other private member of the outer class having its own behaviour and properties.. thnx rishi