Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 482
satheesh.droid Avatar asked Jan 02 '11 16:01

satheesh.droid


People also ask

Can you directly instantiate an abstract class?

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation.

How many times can you instantiate an abstract class?

Abstract class, we have heard that abstract class are classes which can have abstract methods and it can't be instantiated. We cannot instantiate an abstract class in Java because it is abstract, it is not complete, hence it cannot be used.

Can an abstract class be instantiated using the new keyword?

An abstract class cannot be directly instantiated using the new keyword.

Why can't we instantiate an abstract class in C?

We can't instantiate an abstract class because the motive of abstract class is to provide a common definition of base class that multiple derived classes can share.


1 Answers

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.

like image 126
kiritsuku Avatar answered Sep 30 '22 04:09

kiritsuku