Inner classes in my interface - ok, no k, indifferent?

I have an interface and a set of ComparatorS which are only used for objects which implement the interface. So I put the ComparatorS in the interface like so (not actual code because it is for my job):
public interface Abc {
  //Class loader should only do this once so they are basically singleton constants
  public static final Comparator C_1 = new C1();
  public static final Comparator C_2 = new C2();
  //... there is one more
  public String getSomething();
  public String getSomethingElse();
  //First Comparator inner class
  public class C1 implements Comparator {
     private C1(){ }
     //implements appropriate methods checking for instanceof Abc in the compareTo method
    //Compares something (using getSomething())
  /* Second Comparator inner class */
  public class C2 implements Comparator {
    //same thing
    //Compares somethingElse (using getSomethingElse())
} //End interfaceUsage:
Set s = new TreeSet(Abc.C_1);
s.add(abc1);Because the Comparator implementations were specific to objects which implement the interface I felt that was the best way to make that fact clear. If they were over in a separate package it would be confusing that these are for the one interface. If they were in the same package as Abc it wouldn't fit (IMO) because they are more utility type classes.
So it was either that or make them a singleton in their own class files or something like this and I found myself liking this.
Any comments on pros/cons of doing it this way?

I'm confused as to why it would make sense to put the
Comparators 'in' the interface but not in the package
with the interface. You can't put them 'in' the
interface without putting them in the package. In
reality, nesting them in the interface just creates
classes in the interface's package.My whole deal is that after talking it out I see that it is bad for reuse to have something which could be so generic residing in a particular interface (and therefore deduced soon after that in the same package as my interface). Which made me decide not to have the inner classes because it IS in the same package at that point. But I am saying that is bad. As I tried to state before, for the same reason I now think it is bad to have the classes in the interface (not much i.e. no reuse outside of the interface) then it is bad to have it in the same package as the interface (unelegant reuse outside of the package). Because if the getSomething() is getName() that could be used as a comparator for many different objects in different packages. I don't want to limit. This stance was a progression, once I decided not in the interface, I then also decided not in the same package.
Java is strongly typed. If the class isn't an
instance of the class you are casting to (in this
case the interface) it doesn't matter if it has a
method with the same signature. The cast will fail.Yes, of course, but like generics, you are not limited to just one type (Object is the type of the parameter). So I can either use instanceof before casting (not the best way) or I could have private overloads of the compareTo() method, a new one for every type I support and each supported type which has a getName() could come from a couple different packages. Not that generics does it the same way but on top of being about to declare hierachies that a genericized object can deal with you can also have comma delimitted other objects. They don't have to be related by package or hierarchy in generics. So I don't think it would be so bad for my Comparator to be (if it fit that these different types all had the same method needed by my Comparator).
>>
Here's anothe reason not to do that. Let's say that
someone is using the interface. They need to compare
it to something else, if the Comparators are right
there with the interface, they will be likely to find
them. If they are in some other package, they'd have
to know where to go look for them.If that is the case, where I was worried about easy to find then I would go back to using inner classes with each Comparator as a constant. If I was worried about ease of finding where these ComparatorS are over code reuse across packages.
I mean, I think if I am going to tie the ComparatorS so close to a particular Type then I am going to add it as an inner class whether my type was an interface or a class. At least that is what I am thinking now.
>
This is what I am talking about. So many Java
developers treat packages like filing cabinets. I
put things that do this here and things that do that
there. But this is actually not very useful and it
hamstrings your designs.
Java doesn't have a friend class syntax like C++. So
there's no way to say this class over here has access
to this but no one else does. These kinds of
relationships are very desireable. Some classes will
need to access things in another class that shouldn't
be public. You can do this cleanly if they ae in the
same package but not otherwise.But I am not talking about taking an abstract class putting it in pack1 an a subclass in pack2. I am talking about putting a utility class that could eventially work on 50 classes in a place that is playingfield neutral and not in the original type it deals with today only. I am dealing with public accessor methods on my objects.
>
For example. Let's say you want to create a Factory
(I'm using Factory in a loose way here not
necessarily a GoF Pattern) for a public class. You
don't want every class to have access to contructor
because it creates the Object without initializing
all the necessary atttributes. The factory is
specially crafted to do this with protected info and
access rights. If you put the class and the factory
together it;s a snap. You create a package-protected
constructor, some package-protected methods and/or
fields and do it. No class outside the package will
be able to do these dangerous operations. How do you
do this if you have a factory package and a data
object package?That is a whole nother situation I think. In that case it is obvious. I thought my situation was a little less obvious because of the utility nature of the classes (ComparatorS) that I was dealing with.

Similar Messages

  • What is the Use of Inner classes in Interface.

    Hi All,
    Most of us we know that We can define inner classes in the interface. Like
    public interface MyItf{
         Demo d = new Demo();     
         class Demo{
              Demo(){
              //some additional code here
    }Now I have following question in my mind:
    1. An Interface is pure abstract. Then why inner classes inside the interface?
    2. In what scenario, we can utilize these inner classes of interface?
    Plz Share your views on this...
    Thks for ur replies in advance.

    This we cando in defining Demo Class outside.That's no argument. You could write the programs in other languages, so why use Java? Just because you can use a top-level class instead, it's no argument against using an inner class. You also can make all attributes public... you don't o that either (I hope).
    Ok Also
    tell me how to pass an Object in inner class Demo. to
    the method of Interface.
    public abstract TheInterface.Demo doSomething(TheInterface.Demo d);
    Can u give some real time situation where this
    concept can be used.There are only very, very few. Just because it's possible, it doesn't mean it needs to be done or is done often.

  • Interface and Inner Class

    Hi,
    In interface we can't provide method body.
    but we can provide method body like this,
    public interface TestInterface {
         public class Add {
              public int add() {
                   return 100;
    what is the logic behind Inner Class inside interface.
    plz help.Thanks in advance.

    there isn't really any logic to it, it's just something that's semantically possible. there wasn't a conscious decision to allow this, it's just a by-product of the enclosing types mechanism, and while it wouldn't be a good idea to do this, there's no technical reason why it shouldn't be possible, either

  • Using static interface inner class.. how?

    Can anyone tell me how I'm able to use an inner class that is a static interface?
    Specifically I'm getting DocumentEvents through a DocumentListener..
    Then within DocumentEvents there is an inner class which is a static interface called:
    DocumentEvent.ElementChange, I'm trying to use the methods contained within the interface ElementChange.
    Can anyone throw a helping hand as to how I go about this?
    Thanks :)

    public class A ... {
    public static interface B {
    }Just creates a public interface called A.B
    How are you supposed to use this with your DocumentEvent? I can't say

  • Cann't extend a inner class where as can Implement a nested Interface

    i cann't extend a inner class in some other outer class . Where as i can implement the nested Interface in some other class. Why????
    for example:-
    class ABC
    class Inner
    /* class body */
    interface TempInterface
    /* interfacebody */
    class OuterClass
    class InnerTwo extends ABC.inner //(line 1)Will give error
    class InnerTwo implements ABC.TempInterface //(line 2)Will run fine
    the line 1 is going to give compilation error i.e not in the scope but the line 2 will run fine .
    Both of the things are in the same class but giving 2 other results.
    I am not getting sufficient reasons for it.
    Can any one help me????
    Reagrds
    Arunabh

    As far as the language is concerned, the classonly
    exists in the context of an instance of theenclosing
    class.This still exhibits a class/object confusion to me.
    It should be 'instance only exists ...' or 'instance
    can only exist'. The class only exists in the
    scope of the enclosing class, but this is another
    issue.I'm not following what you're saying. The second sentence sounds like you're disagreeing with me. The last sentence sounds like you're agreeing with me.
    A non-static nested class is an instance member, just like an instance method or instance variable. As such, as far as the language is concerned, that class only exists in the context of an instance of the enlcosing class.It's not just instances of the nested class--its the class definition itself that only exists within the context of an instance of the enclosing class. That's why you have to do anEclosingIntstance.NestedClass and can't do EnclosingClass.NestedClass.

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

  • How to call inner class method in one java file from another java file?

    hello guyz, i m tryin to access an inner class method defined in one class from another class... i m posting the code too wit error. plz help me out.
    // test1.java
    public class test1
         public test1()
              test t = new test();
         public class test
              test()
              public int geti()
                   int i=10;
                   return i;
    // test2.java
    class test2
         public static void main(String[] args)
              test1 t1 = new test1();
              System.out.println(t1.t.i);
    i m getting error as
    test2.java:7: cannot resolve symbol
    symbol : variable t
    location: class test1
              System.out.println(t1.t.geti());
    ^

    There are various ways to define and use nested classes. Here is a common pattern. The inner class is private but implements an interface visible to the client. The enclosing class provides a factory method to create instances of the inner class.
    interface I {
        void method();
    class Outer {
        private String name;
        public Outer(String name) {
            this.name = name;
        public I createInner() {
            return new Inner();
        private class Inner implements I {
            public void method() {
                System.out.format("Enclosing object's name is %s%n", name);
    public class Demo {
        public static void main(String[] args) {
            Outer outer = new Outer("Otto");
            I junior = outer.createInner();
            junior.method();
    }

  • Calling functions of the inner class in .java code file

    Hello,
    I created a .java code file in Visual J#.Net and converted it into
    the application by adding the "public static void main(String args[])"
    function.
    I have created the two classes one extends from Applet, and the other
    extends from Frame. The class which I inherited from the Frame class becomes
    the inner class of the class extended from the Applet. Now How do I
    call the functions of the class extended from Frame class - MenuBarFrame
    class. the outline code is
    public class menu_show extends Applet
    ------init , paint action function---------
    public class MenuBarFrame extends Frame
    paint,action function for Menu
    public static void main(String args[])
    applet class instance is created
    instance of frame is created
    Menu , MenuBar, MenuItem instance is created
    and all these objects added
    I have Created MenuBarFrame class instance as
    Object x= new menu_show().new MenuBarFrame
    ????? How to call the functions such as action of MenuBarFrame class - what
    should be its parameters??????
    }

    Here's how I would do it:
    interface Operation {
        public int op(int y);
    class X {
        private int x;
        public X(int x) {
            this.x = x;
        private class Y implements Operation {
            public int op(int y) {
                return x+y;
        public Operation createOperation() {
            return new Y();
        public static void main(String[] args) {
            X app = new X(17);
            Operation f = app.createOperation();
            System.out.println(f.op(-11));
    }Your code, however, has some serious "issues". You typically don't
    instantiate an applet class -- that's the job of the applet viewer or Java plugin
    your browser is using. If you instantiate the applet directly, you're going
    to have to supply it an AppletStub. Do you really want to go that way?
    Again, use an applet viewer or browser, or better yet, why write applets at all?

  • Java Inner classes within the Threading paradigm

    Hi all.
    Im familiar with static nested classes, method local classes, inner classes and anonymous classes.
    But what I am a little perplexed by, is when exactly to use inner classes or static nested classes? (forgetting anonymous classes and method local classes).
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    Also you typically find nested classes within the Threading paradigm, but why?
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.
    Any clarification would be greatly received.
    Thanks and Happy Friday.

    Boeing-737 wrote:
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    I was going to provide some reasons, but when I read the article I found they were already there. Following the DRY principle I'm going to let the article speak for itself.
    Also you typically find nested classes within the Threading paradigm, but why?No, I don't. If that's where you typically find them then you haven't had a varied experience.
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.So carry on doing that, if it works for you.

  • Adding ItemListeners to an object created in an inner class?

    Hi All,
    I was wondering how dow you add ItemListeners to an object, thats created in an inner class of an outer class that implements the item listener interface. Or is it possible? I got around the problem by putting the createBox method in the outer class and calling it from the inner class, but it would be nice to know if you can keep it contained.
    i.e (Assume everythings declared, libs are imported, interface is implemented in outer class etc.)
    public class OuterClass implements ItemListener
        // Stuff
        class InnerClass
            // Yet more stuff
            void createBox (JPanel aPanel)
                 JCheckBox aBox = new JCheckBox;
                 aPanel.add(aBox)
                 // What should this line be ->
                 aBox.addItemListener(whatGoesHere?);
        // More Stuff
    }

    aBox.addItemListener(OuterClass.this);

  • Accessing method in an inner class

    I have a class, which has an Inner Class, which is an extension of AbstractTableModel. The extended TableModel class has a new method, so it looks something like this;
    public class TheOuterClass
        JTable aTable
        TableModel theTableModel
        public initTable
             theTableModel = new MyTableModel();
         public TableModel getModel()
             return theTableModel;
         private class MyTableModel extends AbstractTableModel
                public void myTableModelMethod()
    }So, the idea here is that I have a class that has a table referenced by 'aTable', which uses MyTableModel as the class for it's table model. I have only implemented the basics here. The class also has a method called getModel(), so from a reference to 'TheOuterClass', I can access the table model.
    Now, say I have a reference to TheOuterClass called toc, and I want to access my new method in the table model;
    toc.getModel().myTableModelMethod()The above won't work, because getModel() returns a type of TableModel.
    My question then is how do I cast this to the correct type, so I can access the method 'myTableMethod()'?
    Is for example, the following a legal possibility, because I cannot seem to make it work;
    (toc.getModel().getClass())(toc.getModel()).myTableMethod();The quick fix, I guess is to correct getModel in TheOuterClass, so it returns the correct type, but I am hoping to not do this. (This is part of a larger piece of code obviously, and TheOuterClass is in reality a bean, and I don't wnat to disturb anymore than I have to).
    Any suggestions / ideas would be gratefully appreciated

    You are of course both correct, the class is private, should have spotted that! Doh. Also correct in that this is 'not the most elegant design', but you know the way it is you have to work with what you are given.
    So, I changed the class to public....
    What I had hoped is that the following would work
    ((toc.getModel().getClass())(toc.getModel())).myTableMethod()get a reference to the table model
    (toc.getModel())cast it to the correct type (not sure if this is a valid way to cast??)
    ((toc.getModel().getClass())(toc.getModel()))then call the method.
    This does not compile, it complains about a missing ')', and I'm sure they are all there. My question here then is, Is this a valid way to cast, now that the inner class is public?
    As to why I want to do this, then some explanation is required;
    The table model holds a Vector with all the data in it, some which is not actually in the table (it was originally written this way). My additional method myTableMethod() is intended to help access the data that is not shown in the table.
    Coming back to kajbj's point of creating an interface, I presume what is being suggested is that I create a public interface with the myTableMethod() in it, and make myTableModel implement this interface. Since the interface is public, then I can cast to that. Is this what you meant?
    Thanks for your help so far

  • General class and setting properties vs specific inner class

    This is a general question for discussion. I am curious to know how people differentiate between instantiating a standard class and making property adjustments within a method versus defining a new inner class with the property adjustments defined within.
    For example, when laying out a screen do you:
    - instantiate all the objects, set properties, and define the layout all within a method
    - create an inner class that defines the details of the layout (may reference other inner classes if complex) that is then just instantiated within a method
    - use some combination of the two depending on size and complexity.
    - use some other strategy
    Obviously, by breaking the work up into smaller classes you are simplifying the structure since each class is taking on less responsibility, as well as hiding the details of the implementaion from higher level classes. On the other hand, if you are just instantiating an object and making some SET calls is creating an inner class overkill.
    Is there a general consensus for an approach? I am curious to hear the approach of others.

    it's depends on your design..
    usually, if the application is simple and is not expected to be maintain (update..etc..) than I just have all the building of the gui within the same class (usually..the main class that extends JFrame).
    if the application follows the MVC pattern, than I would have a seperate class that build the GUI for a particular View. I would create another class to handle the ActionEvent, and other event (Controller)
    I rarely use inner class...and only use them to implements the Listerner interface (but only for simple application)..

  • Inner class or not inner class??

    Hi, I've a little problem:
    I want to create bonus objects for my game, all bonus can appears casually during the time of game, so they can be visibles or not visibles.
    If I pick a "bonus cherry", one life is give to the player
    If i pick a "flower bonus", invincibility is give to the player etc etc..
    So, how to build the bonus class??
    I've to define a class with common methods (visibility and animation) and than inner class "cherry" and "flower" ? and they have to be static or not static?
    or I've to implements a bonus interface??

    I want to create bonus objects for my game, all bonus
    can appears casually during the time of game, so they
    can be visibles or not visibles.
    If I pick a "bonus cherry", one life is give to the
    player
    If i pick a "flower bonus", invincibility is give to
    the player etc etc..
    So, how to build the bonus class?? class Bonus
    - int type (flower + invincibility always go together, so you just need one)
    - boolean isVisible
    I've to define a class with common methods
    (visibility)How is "visibility" a method?
    and than inner class "cherry" and
    "flower" ? and they have to be static or not static?Why inner classes? Why different classes at all?
    or I've to implements a bonus interface??Wouldn't be bad per se, but not necessary in this case, you'll only have one Bonus class.

  • Anonymous inner class

    Hello
    In the following piece of code:
    import static tools.Print.*;
    interface ForInner {
         void who();
         String toString();
    class ForInnerWithParameters {
         int i;
         String s;
         ForInnerWithParameters(int i) {
              this.i = i;
    class NackedClass {
         public ForInner inner() {
              return new ForInner() {
                   private int i;
                        print("Inside inner class!");
                        i = 10;
                   public int getI() {
                        return i;
                   public void who() {
                        print("It's me, inner!");
                   public String toString() {
                        return "Anonymous class";
         public ForInnerWithParameters innerWith(int i, final String s) {
              return new ForInnerWithParameters(i) {
                   {     print("i = "+i);
                        print(s);
                        super.s = s;
                   public String getS() {
                        return s;
         public static void main(String[] args) {
              NackedClass nc = new NackedClass();
              ForInner fi = nc.inner();
              fi.who();
              ForInnerWithParameters fiwp = nc.innerWith(91, "Hello");
              print(fiwp.i);
              print(fiwp.s);
    i would like to assign to the variable s (inside ForInnerWithParameters class) the value "Hello" passed as a parameter in the main ( ForInnerWithParameters fiwp = nc.innerWith(91, "Hello"); )
    The method innerWith(int i, final String s) is getting the values 91 and "Hello". Both, the parameter in the method and the parameter in the class are named s. How can I assign the value s ("Hello") to the parameter s inside the class? this.s = s or super.s = s doesn't work. The only solution I found is to change either the name of the parameter s inside the method or the name of the parameter s inside the class.
    I hope the question is clear enough!
    Thanks a lot!

    I would have expected this.s to work, providing you used it every time (including getS()).
    But, to be honest, why bother? It's just pointlessly confusing to use s as your method parameter.

  • How to refer the parent class object from an inner class

    Hi,
    I have a class X, which contains an inner private class Y. Class X has a method getY which returns an object of class Y. Class Y has a method getParent. I want to return the object of parent class from this. The code is like this:
    public inerface IY;
    public class X {
    private class Y implements IY {
    public getParent {
    // ... return the object of parent class which created the object of this inner class
    public IY getY() {
    return new Y();
    Can somebody help me with this...

    interface IY {
    public class X {
        private class Y
            implements IY {
            private X parent;
            public Y(X x)
                parent = x;
            public X getParent()
                // ... return the object of parent class which created the object of this inner class
                return parent;
        public IY getY()
            return new Y(this);
    }Filip

Maybe you are looking for