I have a background in c++ and this syntax looks basically just like
C++. What throws me off is the first line and the last line. I'm
thinking it's a statement because it has ; at the very end, but it looks
like a function definition sqeezed in as an argument of a function call.
Can someone give me a clue?
...
ipField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
ipField.selectAll();
if (connectionStatus != DISCONNECTED) {
changeStatusNTS(NULL, true);
}
else {
hostIP = ipField.getText();
}
}
});
...
Mark - 09 Dec 2005 03:18 GMT
> I have a background in c++ and this syntax looks basically just like
> C++. What throws me off is the first line and the last line. I'm
[quoted text clipped - 17 lines]
>
> ...
This is an anonymous class definition.
Basically you are defining a class that extends FocusAdapter and then
instantiating it in one hit, (without naming the class).
I does exactly the same thing as:
ipField.addFocusListener(new MyFocusAdapter());
where elsewhere you define:
class MyFocusAdapter extends FocusAdapter() {
public void focusLost(FocusEvent e) {
ipField.selectAll();
if (connectionStatus != DISCONNECTED) {
changeStatusNTS(NULL, true);
}
else {
hostIP = ipField.getText();
}
}
});
Roedy Green - 09 Dec 2005 03:25 GMT
>I have a background in c++ and this syntax looks basically just like
>C++. What throws me off is the first line and the last line. I'm
>thinking it's a statement because it has ; at the very end, but it looks
>like a function definition sqeezed in as an argument of a function call.
>Can someone give me a clue?
this is an anonymous class. See
http://mindprod.com/jgloss/anonymousclasses.html

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.
Bjorn Abelli - 09 Dec 2005 08:24 GMT
"donovan" wrote...
>I have a background in c++ and this syntax looks basically
> just like C++. What throws me off is the first line and
> the last line. I'm thinking it's a statement because it
> has ; at the very end,
It is. If you look more closely, you'll see that it ends the following
statement:
ipField.addFocusListener( ... );
> but it looks like a function definition sqeezed in
> as an argument of a function call.
Not quite, but almost... ;-)
You're instantiating an object, which will be the argument of the function
call:
ipField.addFocusListener(new FocusAdapter() {...} );
> Can someone give me a clue?
As FocusAdapter is an abstract class, you need to implement an own subclass
of it, which in Java can be done "anonymously", i.e. without giving it a new
class name, just as you've done.
new FocusAdapter() {
public void focusLost(FocusEvent e) {
ipField.selectAll();
if (connectionStatus != DISCONNECTED) {
changeStatusNTS(NULL, true);
}
else {
hostIP = ipField.getText();
}
}
}
// Bjorn A
donovan - 10 Dec 2005 17:01 GMT