I have learned that we can’t instantiate an abstract class. But today i tested some codes and i feel confused about it.
package MainPackage;
abstract class abstractClass {
abstract abstractClass a_function();
}
public class Src {
abstractClass m;
public abstractClass abstractClassTest() {
return m.a_function();
}
public static void main(String args[]) {
System.out.println("Hello world!");
}
}
Here i create an abstract class abstractClass and return it in the abstractClassTest() function. And it is compiled successfully without errors! IMO before return something, the computer should create an object of that type. And here it should create an object of abstractClass before return m.function(),which i cant understand. i think that we cant instantiate an abstract class means that we cant create an object of an abstract class or we cant new a class(e.g. abstractClass m = new abstractClass() is illegal). But from codes above, it seems that we can create an object of an abstract class. how can it realize? For the code abstractClass m, what does the computer do when it sees the code?We cant say java has instantiate the abstract class m for the code abstractClass m? and if java dont instantiate the class abstractClass, how can it return the object of abstractClass in the code abstract abstractClass a_function();?
Yes, it should compile without errors. It would throw a
NullPointerExceptionon execution though, if you ever calledabstractClassTest, because you never initialize themvariable to refer to an actual instance. In order to do so, you’d have to create a concrete class which subclasses your abstract one.For example:
Note that nothing in your code creates an instance of the abstract class. Just because you’ve got a variable of that type doesn’t mean that an object of that type has been created.