Can someone explain this line of code for me?
SomeAbstractClass variable = new SomeAbstractClass() { };
This properly instantiaties and stores the abstract instance in the variable. What is happening? An anonymous class that extends the abstract class, maybe? Any keywords I can use to look up information about this? (the abstract class also happens to be generic if that has any relevance)
The line above is creating an anonymous subclass of SomeAbstractClass
, which will not be abstract
. Of course, this will work only if the base class has no abstract
methods to implement.
Actually, I cannot visualize an useful instance (besides "documentation" features, see the comment below) of the line above, unless you are implementing and/or overriding methods between curly braces. That is a quite common technique if the base class/interface happens to have few methods to implement and the implementation is simple. You can even refer to the final
variables of the surrounding method and parameters, thus making a closure.
You are creating an anonymous class which is a subclass of your abstract
class. Like was pointed out in comments, you are looking at an anonymous extends.
Something like follows would work if you had abstract
methods to implement:
MyAbstractClass someObjectOfThatClass = new MyAbstractClass(){
@Override
public void someAbstractMethod(){
}
}
You can do the same with interfaces as they can also contain abstract
methods. A practical example would be adding an ActionListener
to a JButton
:
myJButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
// code
}
});
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