0

we know in java that you cant create an instance of an abstract class. but, this works:

public abstract class MyAbstract 
{
    int num  = 10;
}
//and in main class

    public static void main(String[] args) {        
       MyAbstract abstractObject = new MyAbstract() {};
       System.out.println(abstractObject.num);       
    }

output: run: 10

So we can ? In short what is happening here ?

  • `MyAbstract abstractObject = new MyAbstract() {};` creates a **new** sub-class of `MyAbstractClass`. The name of that sub-class? It has none. That is why it is called an *anonymous* class. – Elliott Frisch Apr 15 '18 at 07:41
  • https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html – JB Nizet Apr 15 '18 at 07:41

1 Answers1

0

The syntax

new X(...) { ... }

instantiates an ad-hoc, anonymous class, extending / implementing the class / interface named X.

In your case, the abstract class has all it needs, there are no abstract methods. Therefore, the derived class doesn't need to implement any missing methods.

If you add an abstract method to your abstract class, the example will no longer work. To make it work again, you will have to implement the method in the { ... } section.

public abstract class MyAbstract 
{
    int num  = 10;
    abstract void f();
}

public static void main(String[] args) {        
    MyAbstract abstractObject = new MyAbstract() {
        void f() {
            ...
        }
    };
    System.out.println(abstractObject.num);       
}

In addition, you can pass arguments to an extended base class's constructor by using the () part of the syntax:

public abstract class MyAbstract 
{
    MyAbstract(int argument) {
        ...
    }
    int num  = 10;
    abstract void f();
}

public static void main(String[] args) {        
    MyAbstract abstractObject = new MyAbstract(5) {
        void f() {
            ...
        }
    };
    System.out.println(abstractObject.num);       
}
yeoman
  • 1,671
  • 12
  • 15