Rohan Dmello
Rohan Dmello

Reputation: 83

Java: new AbstractClass(){} What is this declaration called?

In my application there is an abstract class which is used multiple time as follows:

public class Myclass{
    int amount;
    String name;
    public void printResultsFromDB(){
        new MyabstractClass(name){
            @Override
            String getDataFromDB(){
                //some implementation
            }
        };
    }
}

public abstract MyabstractClass{
    String name;
    public MyabstractClass(String name){
        this.name = name;
    }
    abstract String getDataFromDB();
    void execute(){
        //Some implementation
    }
}

I want to know what line number 5 in code called? I know we cannot instantiate an abstract class. Is this declaration called an anonymous class?

Upvotes: 2

Views: 91

Answers (3)

Nathan Hughes
Nathan Hughes

Reputation: 96394

You're not instantiating an abstract class. It's an anonymous inner class that extends MyabstractClass. It still has to provide an implementation of any abstract methods.

It's meant for cases where you want to provide some custom implementation for one case but you don't expect to reuse it anywhere else.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

It is a anonymous class which will allow you to implement an interface.

From the Oracle docs:

The anonymous class expression consists of the following:

  • The new operator
  • The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface
    HelloWorld.
  • Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
  • A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.

Upvotes: 1

MinecraftShamrock
MinecraftShamrock

Reputation: 3574

This is called an anonymous type in Java. It allows you to implement an interface or extend an abstract class without needing a named class for it.

This is especially useful if the interface or abstract class is implemented very often and creating a new class for each implementation would end up in a confusing mess of classes. A good example for this is Java's Runnable interface that simply allows to pass a void method to a method which takes no arguments.

You can find more on this here: http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

Upvotes: 2

Related Questions