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?
Interfaces cannot be instantiated, but rather are implemented. A class that implements an interface must implement all of the non-default methods described in the interface, or be an abstract class.
You can't instantiate an interface or an abstract class because it would defy the object oriented model. Interfaces represent contracts - the promise that the implementer of an interface will be able to do all these things, fulfill the contract.
An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface. A class or struct can implement multiple interfaces. A class can inherit a base class and also implement one or more interfaces.
Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class. An interface can contain any number of methods.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With