Reference Types - Interfaces?
In this tutorial, a reference type is given as
"If you declare a variable using the name of a class for its type, that variable can contain a reference to an object of that class. Such a variable does not contain an actual object, but rather a reference to the class instance, or object, the variable refers to. Because using a class name as a type declares a reference to an object, such types are called reference types."
OK I got it.
But then they say, "Java also allows the use of an interface name to specify a reference type."
What I have understood from this is that a reference to an object of the class which implements the interface can be stored in a reference variable declared with the name of the interface implemented by its class for its type.
But then I was thinking, why would I even do that? When I can simply create the reference variable with the name of the class for its type, why would I do that with an interface being implemented by its class.
Re: Reference Types - Interfaces?
Why? Maybe you want to be able to assign objects of different classes that implement the interface to that variable. Or maybe you don't even know what class the object you're referring to actually is. Sometimes factory methods return instances of private classes that implement known interfaces.