Results 1 to 17 of 17
  1. #1
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default again inner classes

    Besides going over Trees and Tables (hardtime),
    I am recapitulating some basic stuff as well.

    Would this syntax by correct (any comments please):

    Java Code:
    class OuterClass {
    
         private int x = 75;
    
            public void maketoseeInner(String s) {
                InnerClass in1 = new InnerClass();
                in1.seeOuter(s);
            }
                // inner class
                class InnerClass {
    		   public void seeOuter(String s) {
    			    System.out.println("Private variable x is " + x
                                       + " seeing through " + s);
    		   }
                }
    
    
          public static void main(String arg[])  {
              OuterClass outer = new OuterClass();
              OuterClass.InnerClass inner1 = outer.new InnerClass();
              OuterClass.InnerClass inner2 = new OuterClass().new InnerClass();
              outer.maketoseeInner("outer");
              inner1.seeOuter("inner1");
              inner2.seeOuter("inner2");
          }
    
    }
    it prints:
    run:
    Private variable x is 75 seeing through outer
    Private variable x is 75 seeing through inner1
    Private variable x is 75 seeing through inner2
    BUILD SUCCESSFUL (total time: 2 seconds)

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: again inner classes

    If it compiles, the syntax is correct. Whether it does what you intended is another matter. What did you want it to do?
    Get in the habit of using standard Java naming conventions!

  3. #3
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,945
    Rep Power
    19

    Default Re: again inner classes

    "correct"?
    Without knowing what you're trying to achieve that's not something that can be answered.
    It compiles and runs...
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  4. #4
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again inner classes

    That's a good one: "all code that compiles is correct!"

    I am trying things out and here is another one.
    My question is why is the second code example
    also called a anonymous inner class, since one could say that it
    is called "clockticks"?

    Java Code:
    b = new JButton("Click me");
    b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    System.out.println("button pressed");
                }
    });

    Java Code:
    public void Beepbeep() { 
          ActionListener clockticks= new ActionListener() { 
    		// anonymous local inner class ???
                    public void actionPerformed(ActionEvent event) {
          	                Toolkit.getDefaultToolkit().beep(); 
                    } 
         }; 
         Timer t = new Timer(10000, clockticks); 
         t.start(); 
    }
    Last edited by willemjav; 10-18-2013 at 04:59 PM.

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,501
    Rep Power
    5

    Default Re: again inner classes

    Anonymous class simply means there is no explicitly defined class as the target of "new." It has
    nothing to do with whether the instance is saved or not.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  6. #6
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: again inner classes

    The class is not called clockticks; the variable is.
    Get in the habit of using standard Java naming conventions!

  7. #7
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again inner classes

    It is a little cryptic all, because "ActionListener" is an interface, right?
    So one actually instantiates a class or an interface?
    Sure I know that clockticks is a variable of the type interface (ActionListener)
    But at the same time it holds the reference to a instantiated class or interface?
    (can one instantiate an interface?)
    Last edited by willemjav; 10-18-2013 at 06:02 PM.

  8. #8
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: again inner classes

    You can't instantiate an interface directly, but you can create an instance of an anonymous class that implements it.
    Get in the habit of using standard Java naming conventions!

  9. #9
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again inner classes

    wow the sun really starts to shine here....
    kjkrum I know how to do that because I did it many times!
    But how does it really works, because to implement one
    normally uses the "implement" keyword like here:

    Java Code:
    class buttonListener implements ActionListener{
        public void actionPerformed(ActionEvent ae) {
            String cmd = ae.getActionCommand();
                if ((cmd.equals("Click me"))) {
                    System.out.println("yes, button pressed");
                }  
        }
    
    }

  10. #10
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again inner classes

    So I might just take it for granted that when one says:
    new ActionListener() { public void actionPerformed(ActionEvent event) { } };
    one actually instantiates a anonymous class that automatic
    implements the ActionListener interface and its method!

  11. #11
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again inner classes

    OK got it, both are still anonymous classes


    Java Code:
     ActionListener ac = new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    System.out.println("again, button pressed");
                    System.out.println("this is " + this);
                }
            };
            b.addActionListener(ac);
    Java Code:
     b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    System.out.println("again, button pressed");
                    System.out.println("this is " + this);
                }
            });

  12. #12
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: again inner classes

    You got it. The practical difference between those two ways of doing it is if you need to keep a reference to the listener to remove it later.
    Get in the habit of using standard Java naming conventions!

  13. #13
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,435
    Blog Entries
    7
    Rep Power
    20

    Default Re: again inner classes

    Just wait until Java 8 sees the light; those lambda closures take away most of the syntactic verbosity.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    willemjav is offline Senior Member
    Join Date
    Dec 2007
    Location
    Spain
    Posts
    1,075
    Rep Power
    8

    Default Re: again inner classes

    hu, jos?

    Now than the last type of inner class, the static inner class.
    Here is what I found concerning that type of inner class and an example that goes with it:

    However, unlike the inner classes that we used in previous examples, we do not want to have a reference to any other object inside a Pair object. That reference can be suppressed by declaring the inner class static!

    The problem with the example is that, that inner class makes no real sense! Besides being inner class it does not do anything, since I modified that code excluding, the inner class having the same result (see object p2):


    Java Code:
    /**
     * This program demonstrates the use of static inner classes.
     * @version 1.01 2004-02-27
     * @author Cay Horstmann
     */
    public class StaticInnerClassTest
    {
       public static void main(String[] args)
       {
          System.out.println("min = " + Double.MIN_VALUE);
          System.out.println("max = " + Double.MAX_VALUE);
    
          double[] d = new double[20];
          for (int i = 0; i < d.length; i++)
             d[i] = 100 * Math.random();
          // with inner class
          ArrayAlg.Pair p1 = ArrayAlg.minmax(d);
          System.out.println("p1 min = " + p1.getFirst());
          System.out.println("p1 max = " + p1.getSecond());
          //without the inner class
          ArrayAlg p2 = new ArrayAlg();
          p2.minmax2(d);
       }
    }
    
    class ArrayAlg
    {
       /**
        * A pair of floating-point numbers
        */
       public static class Pair
       {
          /**
           * Constructs a pair from two floating-point numbers
           * @param f the first number
           * @param s the second number
           */
          public Pair(double f, double s)
          {
             first = f;
             second = s;
          }
    
          /**
           * Returns the first number of the pair
           * @return the first number
           */
          public double getFirst()
          {
             return first;
          }
    
          /**
           * Returns the second number of the pair
           * @return the second number
           */
          public double getSecond()
          {
             return second;
          }
    
          private double first;
          private double second;
       }
    
       /**
        * Computes both the minimum and the maximum of an array
        * @param values an array of floating-point numbers
        * @return a pair whose first element is the minimum and whose second element
        * is the maximum
        */
       public static Pair minmax(double[] values)
       {
          double min = Double.MAX_VALUE;
          double max = Double.MIN_VALUE;
    
          for (double v : values)
          {
             if (min > v) min = v;
             if (max < v) max = v;
          }
          return new Pair(min, max);
    
       }
    
       public static void minmax2(double[] values)
       {
          double min = Double.MAX_VALUE;
          double max = Double.MIN_VALUE;
    
          for (double v : values)
          {
             if (min > v) min = v;
             if (max < v) max = v;
          }
          System.out.println("p2 min = " + min);
          System.out.println("p2 max = " + max);
    
       }
    }
    So what is the real deal with static inner classes?
    Last edited by willemjav; 10-19-2013 at 02:55 PM.

  15. #15
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,435
    Blog Entries
    7
    Rep Power
    20

    Default Re: again inner classes

    Quote Originally Posted by willemjav View Post
    hu, jos?
    Java 8 allows anonymous function/method closures; an anonymous ActionListener looks something like this:

    Java Code:
    button.addActionListener((al) -> ( /* do someting with the ActionAEvent ae */ });
    My syntax is most likely incorrect; note that the compiler has to figure out a couple of things:

    1) the addActionListener( ... ) method takes an ActionListener as a parameter;
    2) so that funny expression has to be an implementation of an ActionListener;
    3) the ActionListener has a single method;
    4) so that funny expression has to be a method implementation of the actionPerformed(ActionEvent x) method;
    5) so ae has type ActionAEvent.
    6) that funny expression is the body of that method.

    kind regards,

    Jos
    Last edited by JosAH; 10-20-2013 at 10:15 AM. Reason: fixed a few typos ...
    cenosillicaphobia: the fear for an empty beer glass

  16. #16
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: again inner classes

    In the simplest terms:

    Java Code:
    class Outer {
       class Inner {
          ...
          // inside some method of Inner
          System.out.println(this.toString()); // prints the instance of Inner
          System.out.println(Outer.this.toString()); // prints the instance of Outer
       }
    }
    If you declared Inner static, there would be no Outer.this. Instances of Inner would exist independently of instances of Outer. A common example of when this matters is when you don't want instances of the inner class keeping instances of the outer class from being garbage collected.
    Get in the habit of using standard Java naming conventions!

  17. #17
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    11,945
    Rep Power
    19

    Default Re: again inner classes

    Quote Originally Posted by willemjav View Post
    So I might just take it for granted that when one says:
    new ActionListener() { public void actionPerformed(ActionEvent event) { } };
    one actually instantiates a anonymous class that automatic
    implements the ActionListener interface and its method!
    And if you look in the directory with your compiled .class files you will see some class files like <YourClassName>$1.class etc. Those are your anonymous classes created by the compiler.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Association Classes for these classes
    By kevinkhan in forum New To Java
    Replies: 9
    Last Post: 03-21-2012, 05:22 PM
  2. Classes Help!!! two classes with object question.
    By stuckonjava in forum New To Java
    Replies: 16
    Last Post: 02-10-2012, 01:39 AM
  3. Use classes inside of other classes
    By BlankFile in forum New To Java
    Replies: 2
    Last Post: 02-06-2012, 01:51 PM
  4. Three classes help!!
    By arrech326 in forum New To Java
    Replies: 4
    Last Post: 11-24-2009, 06:34 AM
  5. Get name of available classes
    By escuja in forum CLDC and MIDP
    Replies: 0
    Last Post: 07-26-2008, 12:03 PM

Posting Permissions

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