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?

Similar Messages

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

  • 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

  • How to access var in outter class inside inner class

    I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
    import java.io.*;
    public class Kalkulator1{
    int number1,number2,x;
    /* The short way to create instance object for input console*/
    private static BufferedReader stdin =
    new BufferedReader( new InputStreamReader( System.in ) );
    public static void main(String[] args)throws IOException {
    System.out.println("---------------------------------------");
    System.out.println("Kalkulator Sayur by Cumi ");
    System.out.println("---------------------------------------");
    System.out.println("Tentukan jenis operasi bilangan [0-4] ");
    System.out.println(" 1. Penjumlahan ");
    System.out.println(" 2. Pengurangan ");
    System.out.println(" 3. Perkalian ");
    System.out.println(" 4. Pembagian ");
    System.out.println("---------------------------------------");
    System.out.print(" Masukan jenis operasi : ");
    String ops = stdin.readLine();
         int numberops = Integer.parseInt( ops );
    System.out.print("Masukan Bilangan ke-1 : ");
    String input1 = stdin.readLine();
    int number1 = Integer.parseInt( input1 );
    System.out.print("Masukan Bilangan ke-2 : ");
    String input2 = stdin.readLine();
    int number2 = Integer.parseInt( input2 );     
         Kalkulator1 op = new Kalkulator1();
    Kalkulator1.option b = op.new option();
         b.pilihan(numberops);
    System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
    class option{
    int x,y;
         int number1 = Kalkulator1.this.number1;
         int number2 = Kalkulator1.this.number2;
    void pilihan(int x) {
    if (x == 1)
    {System.out.println("Operasi yang digunakan adalah Penjumlahan");
            int y = (number1+number2);
            System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
             int y = (number1-number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
             int y = (number1*number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
             int y = (number1/number2);
             System.out.println("Hasil dari operasi adalah =" + y);}
    else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
    }

    Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
    In future place code tags around your code to make it retain formatting. Highlight code and click code button.

  • Need help trying to use close button and i really like to know why it off

    need help trying to use close button and i really like to know why it off

    And in English? You need to explain better.
    Mylenium

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

  • 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

  • Final class and private constructor

    Whats the difference in a final class and a class with private constructot?
    If we can make a class non-extendable by just giving private constructor then whats the advantage of final class? (I know final is very useful for many other things but just want to get info in this contaxt)

    You can extend a class with a private constructor,I'm not sure about that. The compiler will complain.
    KajThat depends on the signature of the private constructor.
    If it's the no-arg constructor and you don't declare another constructor which you explicitly call from your derived class you will indeed get an error.
    If however you never call it (and there's no way it can implicitly get called) from a derived class there should be no problem.
    class Private1 {
         private int q;
         private Private1() {
         public Private1(int i) {
              q = i;
         public void print() {
              System.out.println(q);
    public class Public1 extends Private1 {
         public Public1() {
              super(1);
         public static void main(String[] args) {
              new Public1().print();
    }for example compiles and runs perfectly.
    But remove the call "super(1);" from the constructor and it will fail to compile.

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

  • Please give me the information when to use inner classes in applications

    HI,
    please give me when to use the innerclasses

    > HI,
    please give me when to use the innerclasses
    Use them when you want to create a class within another class.
    Now gimme all 'er Dukes!!!

  • Class using another class access

    I'm sure this is not difficult, but finding the answer has been quite elusive for me. I'd like to start simple. I have two classes, Place and Address that look like this:
    public class Address{
       private String street;
       private String town;
      ...some other address stuff
       public void setStreet(String streetname) {
         this.street = streetname;
    public String getStreet() {
         return this.street;
    ...same f or town and others
    }//end of Address class
    Now I have the Place class:
    public class Place {
       private String name;
       private Address address **here begins my questionsI currently have the private address declaration as:
       private Address address = new Address();1. Is this Address address declaration correct, or should it be different?
    2. Do I, create setAddress and getAddress methods in the Place class, and if so, so they just use the object 'address', i.e. 'return address;' ?
    After I understand how to do these two things, I need help in accessing the address parts, like street and town, from a third class, the PlaceTest class which has a 'main' method.
    Thanks in advance for your help.

    Check out this as a for-instance. Here is a sample Address class
        class Address
            private String street;
            private String town;
            private String state;
            private String zip;
            public Address(String street, String town, String state, String zip)
                this.street = street;
                this.town = town;
                this.state = state;
                this.zip = zip;
            public void setStreet(String street)
                this.street = street;
            public String getStreet()
                return street;
            @Override
            public String toString()
                return street + ", " + town + ", " + state + ", " + zip;
        }And here is a Place2 class that uses Address
    class Place2
        private Address address;
        public Place2() {}
        public Place2(Address address)  // <== **** here I'm passing an addresss param
            this.address = address;
        public void setAddress(Address address) // <== **** and here too
            this.address = address;
        @Override
        public String toString()
            return address.toString();
        public static void main(String[] args)
            Place2 myPlace = new Place2(
                new Place2().new Address("100 Main St", "AnyTown", "IL", "60022"));
            System.out.println("My address is: " + myPlace);
            // let's change the address:
            Address address2 = new Place2().new Address("123 First St", "Podunckville", "State of Confusion", "10101");
            // then pass this address to myPlace
            myPlace.setAddress(address2);
            // then show it
            System.out.println("My new address is: " + myPlace);
    }

  • Java class uses another class in a Jar file (How do I make Java see it)?

    I am trying to figure out how do I make Javac see the thinlet.class in the thinlet.jar.
    I have developed an XUL xml interface and a java program that calls the interface shown below:
    //package thinlet.demo;
    import thinlet.*;
    public class UI extends Thinlet
    { public UI () throws Exception {add(parse("UI.xml"));}
    public static void main(String[] args) throws Exception
    { new FrameLauncher("UI", new UI(), 600, 600); }}
    when I do the normal compile, I get an error:
    UI.java:4: cannot find symbol
    symbol: class Thinlet
    public class UI extends Thinlet {
    ^
    UI.java:7: cannot find symbol
    symbol : method parse(java.lang.String)
    location: class thinlet.demo.UI
    add(parse("UI.xml"));
    ^
    UI.java:12: cannot find symbol
    symbol : class FrameLauncher
    location: class thinlet.demo.UI
    new FrameLauncher("UI", new UI(), 600, 600);
    ^
    3 errors
    This thinlet class should be in the thinlet.jar that I have added the directory to the path, the directory and jarfile name to the System CLASSPATH and it couldn't see it. So finally I tried putting the thinlet.jar in the same directory to no avail. I've searched the web for some time an cannot find anything that specifically speaks to compiling a program that has parent classes in a Jar.
    Any help is definitely appreciated.

    This thinlet class should be in the thinlet.jar that I have added the directory to the path, the directory and jarfile name to the System CLASSPATH and it couldn't see it. So finally I tried putting the thinlet.jar in the same directory to no avail. I've searched the web for some time an cannot find anything that specifically speaks to compiling a program that has parent classes in a Jar.
    Any help is definitely appreciated.You just still haven't provided the jar in the classpath, or you're not using the right class name. Is the class really named thinlet.Thinlet? Or are you thinking "import thinlet.*" means to import all classes in a jar named thinlet.jar? Because the latter is not true. You need to import classes, not jar file names.

  • How to access super of enclosing class from inner class?

    Hello,
    I'd like to access Base.foo() from inner class in overridden Improved.foo(), but seem unable:
    public class InnerSuper {
         public static class Base {
              protected int foo() {
                   return 1;
         public static class Improved extends Base {
              @Override
              protected int foo() {
                   return Integer.parseInt(new Object () {
                        public String toString() {
                             return "1"+foo() ;
                   }.toString());
         public static void main(String[] args) {
              System.out.println(new Improved().foo());
    }The code above does not work, as it recursively calls Improved.foo() where I'd like it to call Base.foo(). What syntax construct should I use? Improved.this would be the same thing, Improved.super does not exist.
    I came up with a work around: adding a method baseFoo() to Improved and call that in the inner class:
       int baseFoo() {
          return super.foo();
       } but remain wondering if that is necessary?

    Indeed, Improved.super.foo() is allowed. My Eclipse syntax highlighting seems to have the same opinion as you: "are you sure you want to write that kind of code?" and leaves the read underlining for a syntax error on for just a second longer.
    This is where I am now:
         public static class DeferredExecSubroutineCall extends SubroutineCall {
              RelayExecutor relay;
              public DeferredExecSubroutineCall(RelayExecutor relay) {
                   this.relay = relay;
              @Override
              protected String execute(final IFDSOC fd, final String commandText) {
                   Future<String> f = relay.submit(new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                             return DeferredExecSubroutineCall.super.execute(fd, commandText);
                   try {
                        return f.get();
                   } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                   } catch (ExecutionException e) {
                        if (e.getCause() instanceof RuntimeException) {
                             throw (RuntimeException) e.getCause();
                        } else {
                             throw new RuntimeException(e.getCause());
         }which is my current effort of adding concurrency to an existing project. I find it quite elegant but I am interested to hear from you...

Maybe you are looking for