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?
You are mixing up object and reference.
test
here is a reference to a anonymous class that extendsAbstractTest
, the above code is like saying:test
is an object of an anonymous concrete sub-class ofAbstractTest
(note that it implements all the abstract methods ofAbstractTest
), which is why this sub-class can be instantiated.On the other hand,
wouldn't pass compilation, since that would be an attempt to instantiate an abstract class.
Abstract Class in my opinion needs to be explained together with Interface.
Interface allows you to specify operations that are supported/allowed on objects with that interface. More specifically Objects are instances of a Class which implements that Interface. Defining an interface allows you to describe a group of different classes of objects so that other objects can interact with them in the same manner.
Abstract Class is one step between interface and a Class (loosely speaking). Abstract Class allows you to specify operations that are supported by classes that extend it, but it also allows you to implement (some of) those operations. This way you can implement common methods for a group of classes in that abstract class. Other methods in the abstract class that are not implemented (aka abstract methods) need to be implemented by the class that extends it. The fact that you didn't implement all methods on an Abstract class naturally means you can't instantiate it (create an object of such class). There are other useful implementations for Abstract classes (i.e. callbacks).
In your example what you see there is that you are not really trying to just create an object that Abstract class you are also providing implementation of abstract method onClick();
That is the only way you can "create an instance of the abstract class" - technically speaking you are creating an instance of an Anonymous class (that is extending your abstract class) for which you provide implementation of inherited abstract methods.