Search code examples
javaoopinstanceabstract-class

Can we create an object of abstract class?


I am just confused about abstract class concept. Please clear my doubt. Definition of Abstract class says we can not create object of such class, then what we called like A a = new A() { }. Example is below:

public abstract class AbstractTest {
    public abstract void onClick();
    public void testClick() {

    }
}

public class A {
    AbstractTest test = new AbstractTest() {
        @Override
        public void onClick() {

        }
    };
}

Then test is a object or what?


Solution

  • test is an object of an anonymous concrete sub-class of AbstractTest (note that it implements all the abstract methods of AbstractTest), which is why this sub-class can be instantiated.

    On the other hand,

    AbstractTest test = new AbstractTest();
    

    wouldn't pass compilation, since that would be an attempt to instantiate an abstract class.