简体   繁体   中英

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)

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
                }
            });

Java gives you the ability to create anonymous subclasses inline. You often see this in the context of anonymous inner classes with Swing event handling, but there are many other applications as well.

In your example, you are creating a class that extends SomeAbstractClass anonymously and assigning it to a SomeAbstractClass reference. It would be just as if you created a separate class like this

public class SomeConcreteClass extends SomeAbstractClass {
}

and later did this

SomeAbstractClass variable = new SomeConcreteClass();

As noted by @Stefano, your approach only works if your anonymous concrete class has no abstract methods, which would be true because SomeAbstractClass has no abstract methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM