It is already implemented by whoever wrote the class that represents a type returned by sharedPreferences.edit().
In this example there is Animal interface. Animal can make a sound.
The method makeSound() is abstract.
Now, you are given RandomAnimalFactory. It returns some random animal.
For a moment assume this is in a different file and you can't see the source of this class.
All you can now is that it returns an instance of Animal.
Also, imagine there is an approproate javadoc.
The code you write is the Temp class.
Assume you need a random animal, so you can create an instance of RandomAnimalFactory and call getRandomAnimal() on it.
This returns you an Animal instance.
What class it is? You don't know. At least not until you checks the source of RandomAnimalFactory or call animal.getClass().
There is a name for that construct: an anonymous class. You can read about it in the Java™ Tutorials.
Paweł Baczyński wrote:. . .. . .
Paweł Baczyński wrote:
Animal is an interface.
The construct I used is called anonymous class and is perfectly legal.
Campbell already mentioned it.
Perhaps using anonymous classes as an example is too complex? Why not something simple like an ArrayList instance and the List interface?
John Losty wrote:what is the diference between
They both return an animal reference but the first will not compile??
Sorry for confusing you with anonymous classes. Forget about it for a moment.
First line tries to create an object of type Animal. This is illegal.
Second line returns a reference of type Animal. It is legal.
Also, note that this is illegal:
But this is legal:
In the second example an instance of a class with no name (anonymous class) that happens to implement Animal interface is created.
You can instantiate an object of a concrete class that implements that interface - either directly - or via inheritance. Abstract classes may implement interfaces, but by definition cannot be themselves instantiated.