Results 1 to 2 of 2
  1. #1
    parthu_lkp is offline Member
    Join Date
    Aug 2009
    Posts
    1
    Rep Power
    0

    Unhappy an API can return objects without making their classes public

    How can we justify the below stmt

    "an API can return objects without making their classes public"
    (By using Static Factory methods)

    If we justify the above stmt, can we access Objects in other packages also or those are valid in the same pack.?????

    Could you please explain with example(without taking j2se/j2ee classes)???

    thx
    Parthu

  2. #2
    dlorde is offline Senior Member
    Join Date
    Jun 2008
    Posts
    339
    Rep Power
    7

    Default

    If the API returns an interface (as they generally should), then the caller doesn't need to know which class is implementing the interface. This means the class itself need not be public - it can even be a local anonymous class declared and instantiated inside the method being called; this is how iterators are provided by some collection classes. You don't have to use static factory methods, although they are useful for returning objects of different types depending on the context.

    For example, the AbstractList class returns its iterators like this:
    Java Code:
    public Iterator<E> iterator() {
        return new Itr();
    }
    
    public ListIterator<E> listIterator() {
        return listIterator(0);
    }
    
    public ListIterator<E> listIterator(final int index) {
        if (index<0 || index>size())
            throw new IndexOutOfBoundsException("Index: "+index);
    
        return new ListItr(index);
    }
    The classes Itr and ListItr are private inner classes that implement the Iterator and ListIterator interfaces respectively.
    Last edited by dlorde; 08-11-2009 at 02:02 PM.

Similar Threads

  1. classes as objects
    By kroiz in forum New To Java
    Replies: 4
    Last Post: 07-25-2009, 05:22 AM
  2. Return objects called
    By MV1 in forum New To Java
    Replies: 7
    Last Post: 03-11-2009, 07:16 AM
  3. How to access private data types from public classes?
    By kevzspeare in forum New To Java
    Replies: 3
    Last Post: 03-07-2009, 04:19 AM
  4. How to return to next line of code after calling a public class?
    By devdevi@comcast.net in forum New To Java
    Replies: 1
    Last Post: 02-02-2009, 06:46 PM
  5. Need help with Java classes for making a program.
    By TheDarkReverend in forum Advanced Java
    Replies: 2
    Last Post: 11-28-2008, 04:50 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •