Re: Using Interfaces ?
- From: Joe Schlobotnick <joeIsNot@xxxxxxxx>
- Date: Sun, 25 Feb 2007 14:39:17 -0500
TonyB wrote:
"TonyB" <tonyb@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote in message news:dFcEh.6455$ud2.5085@xxxxxxxxxxxxxxxxxxxxxxxxxYes, you do seem to understand correctly. Indeed, it's very accurate to say you're declaring a "type" (although I wouldn't say "for a class's methods...see below.) Any class that implements an interface is said to have an "is a" relationship with that interface. Dog "is a" Animal, Cat "is a" Animal, etc. (where Animal is an interface that both Dog and Cat implement.)I've started java recently and I'm having some problems using interfaces in real world cases.
Say I have an interface, "exampleinterface" declaring a list of methods. I write a class, "example1class" which implements the interface methods 1 for 1. I can compile the class ok since all methods required by the interface are implemented in the class. I could write another class which also implements interface "exampleinterface" called "example2class".
Now if I want to use an object of type "example1class" in my code, I create it using "exampleobject = new example1class" where exampleobject is declared as type "example1class". Similarly I could use "example2class" also.
But I'm puzzled as to how to create an object that uses the interface "interfaceexample", and how to specify which of the two possible classes that implement the interface are actually used in my code ?
Thanks
Tony
I think I've answered my own question. An interface is really declaring a type for a class's methods , so that when I use a class based on that interface, it is type checked that it meets the requirements defined in the interface ?
So I could say
exampleinterface object 1 ;
exampleinterface object 2 ;
...
object1 = new example1class();
object2 = new example2class();
If this compiles I know that both objects implement the required methods.
Do I understand this correctly ?
Tony
One slight clarification. It's possible to have an empty interface, one without method signatures. So while it's usually the case that implementing an interface implies the existence of certain methods in the implementing class, it's not necessarily so. Such interfaces are often referred to as "tagging" interfaces; they simply "tag" a class as being a member of a group.
...Joe
.
- References:
- Using Interfaces ?
- From: TonyB
- Re: Using Interfaces ?
- From: TonyB
- Using Interfaces ?
- Prev by Date: Re: Unchecked compiler warning
- Next by Date: Re: ensuring unique object
- Previous by thread: Re: Using Interfaces ?
- Next by thread: Re: Using Interfaces ?
- Index(es):
Relevant Pages
|