Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java initializing abstract classes

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)

like image 916
user2651804 Avatar asked Feb 14 '23 21:02

user2651804


2 Answers

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.

like image 170
Stefano Sanfilippo Avatar answered Feb 17 '23 10:02

Stefano Sanfilippo


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
                }
            });
like image 30
An SO User Avatar answered Feb 17 '23 09:02

An SO User