The following java code works fine.
public static void main(String[] arg){
JPanel p = (new JPanel());
p.add( new Object(){
JButton f(JButton x){
x.setEnabled(false);
return x;
}}.f(new JButton("B")) );
JFrame w = new JFrame("W");
w.add(p);
w.pack();
w.setVisible(true);
}
If the method is changed to its generic form the program fails.
public static void main(String[] arg){
JPanel p = (new JPanel());
p.add( new Object(){
<T> T f(T x){
x.setEnabled(false);
return x;
}}.f(new JButton("B")) );
JFrame w = new JFrame("W");
w.add(p);
w.pack();
w.setVisible(true);
}
Why does it fail? How can you define generic methods within an anonymous class?
This question is for learning purposes.
Yes, you can define a generic method in a non-generic class in Java.
Because the EventHandler<ActionEvent> interface contains only one method, you can use a lambda expression instead of an anonymous class expression. See the section Lambda Expressions for more information. Anonymous classes are ideal for implementing an interface that contains two or more methods.
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time. A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.
T
's erasure is Object
, which does not have setEnabled
. It works if you give it a bound of JComponent
, which definessetEnabled
:
public static void main(String[] arg) {
JPanel p = (new JPanel());
p.add( new Object(){
<T extends JComponent> T f(T x){
x.setEnabled(false);
return x;
}}.f(new JButton("B")) );
JFrame w = new JFrame("W");
w.add(p);
w.pack();
w.setVisible(true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With