Are you saying that at run time we cannot be sure what methods a class has that implements an interface? So we instead make a reference specifying that class so we'll know what methods it supports?
No. I was trying to give an example for coding in this manner, this one is more in depth.
Say based on certain user input that we want to use a
to structure our data, and on other user input a
, because structure is not important. So somewhere in our code, we might have a statement like this:
Code:
if (userWantsStructure) {
treeSet = new TreeSet ();
}
else {
hashSet = new HashSet ();
}
However, this makes the code twice as long, because whenever we want to add data, we have to see which type the user wants, because we have to use either the
or
. So code to add data would look like this:
Code:
if (userWantsStructure) {
treeSet.add (data);
}
else {
hashSet.add ();
}
This is where your question comes to the rescue. Both of these classes ,
and
, implement
. Also, most of the times we need to use these objects, we are using methods defined in
.
By creating a variable of type
, like so:
and initializing it similar to the example above:
Code:
if (userWantsStructure) {
set = new TreeSet ();
}
else {
set = new HashSet ();
}
we can now do anything that
defines, no matter whether
refers to a
or a
. So the code to add data, no matter which object
references, would be:
If we wanted to do something specific with
or
, then we would have to do the check for which type
references, cast
to that type, and then access the methods needed, shown below:
Code:
if (set instanceof TreeSet) {
TreeSet treeSet = (TreeSet) set;
//Do something with treeSet here
}
else {
HashSet hashSet = (HashSet) set;
//Do something with hashSet here
}
Also is it true you can't actually create an instance of an interface?
Technically yes. This is a little off topic, but anonymous classes are an exception to this. You can create an anonymous class that implements an interface and this violates direct instantiation of interfaces. Here is an example, using
, since that's how I use it most.
Code:
ActionListener listener = new ActionListener () {
public void actionPerformed (ActionEvent event) {
//Code here for actionPerformed
}
};
I'm not quite sure what else to talk about, let me know if you have any further questions.
MarsChelios