Results 1 to 4 of 4

Thread: Anonymous class

  1. #1
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Posts
    115
    Rep Power
    0

    Default Anonymous class

    I am interested in using anonymous classes. I read somewhere that anonymous classes should be preferred when class have a very short body an only one instance of that class is needed.

    Can some one guide me about the syntax and working of anonymous classes.

    Thanks in advance.

  2. #2
    Join Date
    Dec 2007
    Posts
    24
    Rep Power
    0

    Default

    I think its useful 2 u

    Anonymous Classes in Java

  3. #3
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    8

    Default

    More (pseudo code) examples:
    Java Code:
    JButton button = new JButton("say something");
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            System.out.println("something");
        }
    });
    SpinnerNumberModel model = new SpinnerNumberModel(10,0,100,1);
    JSpinner spinner = new JSpinner(model);
    spinner.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            int value = ((Integer)((JSpinner)e.getSource()).getValue()).intValue();
            tellSomeone(value);
        }
    });
    // Although not an anonymous listener in the strict
    // sense, this approach can make sense sometimes:
    JButton someButton = new JButton("compute");
    final JTextField textField = new JTextField(12);
    ActionListener al = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int n = Integer.parseInt(textField.getText());
            doSomething(n);
        }
    };
    someButton.addActionListener(al);
    textField.addActionListener(al);

  4. #4
    ravian is offline Senior Member
    Join Date
    Nov 2007
    Posts
    115
    Rep Power
    0

Similar Threads

  1. Replies: 0
    Last Post: 04-02-2008, 07:04 AM
  2. Replies: 0
    Last Post: 02-17-2008, 09:03 AM
  3. Replies: 0
    Last Post: 02-17-2008, 09:01 AM
  4. Inner class accessing outer class
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-17-2008, 08:59 AM
  5. Name of Anonymous class
    By eva in forum New To Java
    Replies: 1
    Last Post: 12-31-2007, 01:07 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
  •