Can you instantiate an Interface in Java
Solution 1
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface.
So what is happening is that getSharedPreferences
returns an object that implements that interface. The type of the returned object is not important. What is important is that it implements all the methods for that interface, so it can be used as an SharedPreferences
Solution 2
SharedPreferences
is a reference, but you are not creating a SharedPreferences
object. Rather, you are creating an object that is of that type; namely, an implementation of that type. e.g have a look at the following reference where you can use an Interface as a reference type for an instance which is actually an implementation of the reference type interface. http://docs.oracle.com/javase/tutorial/java/IandI/interfaceAsType.html
Solution 3
SharedPreferences pref = Context.getSharedPreferences("some value", 0);
in this code the type of your object is SharedPreferences but the instance is a class that implements the interface of SharedPreferences this is a basic concepts of OOP
Solution 4
However we do not use this interface as I have read about in the books, we do not create a class and implement SharedPreferences.
You do not create a class that implements this interface, because somebody has already created one for you. You use this class via its interface, without even knowing the class name. That's what interfaces are for.
drlobo
Updated on July 09, 2022Comments
-
drlobo almost 2 years
Can you instantiate an Interface in Java? I know the quick answer is "no". But there is something I am not understanding well.
What is happening here?
SharedPreferences is a public Interface. However we do not use this interface as I have read about in the books, we do not create a class and implement SharedPreferences. Instead we use this API like this:
SharedPreferences pref = Context.getSharedPreferences("some value", 0);
So what is really happening in this code?
I think its like getSharedPreferences() is creating a
SharedPreferences
object which we can then use and manipulate.But
SharedPreferences
is an Interface ... and I was told you have to implement Interfaces not create object of them. What is this in Java??When I look at a Java API and I see a class as defined as Public Interface. How do I know when to implement that interface or when to create this type of object from it?