Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Anonymous Inner class

Tags:

java

rb.addActionListener(new ActionEvent(ae) {
   public void actionPerformed(ActionEvent ae) {
     nowCall(ae);
    }
});

Another way

Thread th=new Thread(Runnable r) {
  public void run() {
    // do something
  }
};

// notice the ending of above 2 snippets

I am really confused seeing these two.It seems there is no exact pattern to declare an anonymous inner class.

please explain the syntax for anonymous inner class.

like image 817
saplingPro Avatar asked Dec 16 '22 15:12

saplingPro


2 Answers

The second isn't valid, as far as I can see and test.

What would be more common would be to create a new Runnable implementation:

Thread th=new Thread(new Runnable() {
  @Override
  public void run() {
    // This implements Runnable.run
  }
});

Now you could just override the run method of a normal thread:

Thread th=new Thread() {
  @Override
  public void run() {
    // This overrides Thread.run
  }
};

... but personally I prefer specifying the Runnable separately when creating a thread.

Now the difference that you noticed at the end is simply whether the expression is used as an argument (e.g. to the addActionListener method or the Thread(Runnable) constructor, or whether it's just assigned directly to the variable. Think of the whole new TypeName() { ... } as a single expression, and it's just the difference between:

Thread th = expression;

and

Thread th = new Runnable(expression);
like image 178
Jon Skeet Avatar answered Dec 26 '22 17:12

Jon Skeet


There is the difference that in the first case your passing it as an parameter to a method and in the second example you're storing it in a local variable.

So you can't really compare both examples against each other.

like image 20
RoflcoptrException Avatar answered Dec 26 '22 15:12

RoflcoptrException