Can we instantiate an abstract class directly? [duplicate]

I have read we can only instantiate an abstract class by inheriting it, but we cannot instantiate it directly.
However, I saw we can create an object with the type of an abstract class by calling a method of another class.
For example - LocationProvider is an abstract class, and we can instantiate it by calling getProvider() function in the LocationManager class:

LocationManager lm = getSystemService(Context.LOCATION_PROVIDER);
LocationProvider lp = lm.getProvider("gps");

How is the abstract class instantiate here?


You can't directly instantiate an abstract class, but you can create an anonymous class when there is no concrete class:

public class AbstractTest {
    public static void main(final String... args) {
        final Printer p = new Printer() {
            void printSomethingOther() {
                System.out.println("other");
            }
            @Override
            public void print() {
                super.print();
                System.out.println("world");
                printSomethingOther(); // works fine
            }
        };
        p.print();
        //p.printSomethingOther(); // does not work
    }
}

abstract class Printer {
    public void print() {
        System.out.println("hello");
    }
}

This works with interfaces, too.


No, you can never instantiate an abstract class. That's the purpose of an abstract class. The getProvider method you are referring to returns a specific implementation of the abstract class. This is the abstract factory pattern.


No, abstract class can never be instantiated.