Tags: implement, implementationi, interface, java, methods, programming
An Interface
On Java Studio » Java Programming
25,317 words with 21 Comments; publish: Thu, 20 Sep 2007 07:36:00 GMT; (15093.75, « »)
Hey I got a ?,
Is there anything more to the interface than just implementation?
I mean I can see that you need to implement all methods in an interface in order to use it, and it forces the programmer to implement these methods but what is the purpose of this? If there is never an instance of an interface how does it do anything? Does it need to be used in conjunction with an object of some sort that will expect the interface method?
Please Explain....
http://java-program.developerfaqs.com/q_java-programming_14731.html
All Comments
Leave a comment...
- 21 Comments

- it just sounds to me like an interface does a whole lot of nothing besides forcing implementation of methods#1; Mon, 09 Jul 2007 18:49:00 GMT

Well, besides forcing an implementation of methods, you can stick constants in there also.
It is also used for comparison of instances. i.e. If you have 5 classes that implement an interface then all 5 of your objects can be compared with the "instanceof" keyword.
Since Java doesn't have multiple inheritance (i.e. you can't directly subclass from 2 separate object) interfaces allow you to leverage the concept of polymorphism. It also allows you to use multithreading without having to subclass the Thread class directly. By making your class implement the Runnable interface you tell the JDK that your class has a run() method that can be spun off into another thread.
The JDK also utilizes the concept of "marker" interfaces that do nothing other than to let the compiler know that the class is "special" in some way, i.e. That the class is Serializable, Clonable, Comparable, etc.
#2; Mon, 09 Jul 2007 18:49:00 GMT

You have already mentioned pretty much what an Interface is for. It specifies a set of methods that must be implemented by and class that implements it. Let's assume I create a Stack interface, I can defined Push, Pop, Peek. Then I can create other classes that implement this Interfaces (i.e. LinkedListStack, ArrayStack).
I can then create a reference object of the Interface type (Stack) to point to any class that implements the interface and call any of the methods defined in the interface.
interface Stack
{
public void Push(Object obj);
public Object Pop();
public Object Peek();
}
class ArrayStack implements Stack
{
public void Push(Object obj){ System.out.println("ArrayStack::Push"); }
public Object Pop(){System.out.println("ArrayStack::Pop"); return new Object(); }
public Object Peek(){System.out.println("ArrayStack::Peek"); return new Object(); }
}
class LinkedListStack implements Stack
{
public void Push(Object obj){ System.out.println("LinkedListStack::Push"); }
public Object Pop(){System.out.println("LinkedListStack::Pop"); return new Object(); }
public Object Peek(){System.out.println("LinkedListStack::Peek"); return new Object(); }
public static void main(String args[])
{
Stack s = new ArrayStack();
s.Push("S");
s.Pop();
s.Peek();
s = new LinkedListStack();
s.Push("T");
s.Pop();
s.Peek();
}
}
#3; Mon, 09 Jul 2007 18:49:00 GMT

Interfaces make use of reusablility. Take KeyListener, for example. It contains code to know how to detect when a key is pressed, so rather that write this code for each class, that you write in which you want to detect key presses, you use the interface instead. Even if you don't use all of the interface's methods, you still need to add them to your code because the internal code for the listener is looking for those particular methods in your code. It is how the interface communicates with your class.
#4; Mon, 09 Jul 2007 18:49:00 GMT

Ah young grasshopper ...when you can snatch these pebbles from my hand before it closes ...then my son you will be ready to understand the great mystery known as 'the interface'.
It allows polymorphic behaviour.
Class Boat and Class Car can both implement Steerable. When other parts of the main application code needs to steer something, you can pass in either Boat or Car and they will cast correctly down to type Steerable ...polymorphic like! One way to look at it ...although you should never say these words out loud ...is that it allows for multiple inheritance in Java. Although we are usually inheriting generic actions or behaviours rather than actual identity.
Beyond that ...it seems interfaces take awhile to pull out of the fog when first beginning Java. Look at RMI examples ...that's when interfaces really become obvious, at least I thought so anyway.
Hope this helps ...I really don't want to write a book about it with all the others available from chapters already. Study some design patterns too ...many patterns utilize interfaces and when you know what you are trying to do, it becomes more obvious why the interface was neccessary to do it. Good luck.
And you should have known better than to crosspost this young grasshopper.
#5; Mon, 09 Jul 2007 18:49:00 GMT

- k here is a ?, lets say I don't implement runnable, lets say I just use the run method, could I still make a thread without implementing runnable? If not why not? Because what recognizes the run method if all your doing is implementing runnable?#6; Mon, 09 Jul 2007 18:49:00 GMT

- I see your point on conversions....#7; Mon, 09 Jul 2007 18:49:00 GMT

- for these "conversions" does it only work with the methods that you implement? I would think it would...#8; Mon, 09 Jul 2007 18:49:00 GMT

- > k here is a ?, lets say I don't implement runnable,> lets say I just use the run method, could I still make> a thread without implementing runnable? The best way to learn is to try. Did you try?#9; Mon, 09 Jul 2007 18:49:00 GMT

- who ever wrote that code, that made alot of sense as far as object reusability..... :-) also can I get an example of this casting that someone spoke of, that interests me to...#10; Mon, 09 Jul 2007 18:49:00 GMT

- is reusing an object like that more efficent than declaring a new one?#11; Mon, 09 Jul 2007 18:49:00 GMT

- you can only reuse the objects methods that are declared in the interface correct?#12; Mon, 09 Jul 2007 18:49:00 GMT

If the Java people wanted to allow that, then they would have. However, to determine whether or not a particular object has a method with a certain signature, reflection must be used. Reflection has a lot of overhead. Requiring a class to implement the Runnable interface to be used in a thread allows the ability to make sure that the run() method exists at compile time, since (o instanceof Runnable)==true insures that the run() method has been implemented. Basically, interfaces connect method signatures to a type, so the existance of those methods can be insured by type-checking.
#13; Mon, 09 Jul 2007 18:49:00 GMT

- I said it and instead of giving out answers, it is far more instructive if you read up on it. That way, you'll be sure to learn it.Good luck.#14; Mon, 09 Jul 2007 18:49:00 GMT

- aww they did not have this in any of my reading material...#15; Wed, 18 Jul 2007 19:30:00 GMT

- thoughts#16; Wed, 18 Jul 2007 19:30:00 GMT

> is reusing an object like that more efficent than
> declaring a new one?
Reusing that reference object was just to show that you may use a reference of the interface type to point to any object that implements that interface.
> you can only reuse the objects methods that are
> declared in the interface correct?
If you use the generic Stack reference, Yes. If you use a specific reference (e.g. LinkedListStack) you may call any method in the class.
#17; Wed, 18 Jul 2007 19:30:00 GMT

Hi, thoughts? Yes actually, some. See if you can make anything out of this regarding the polymorphic qualities of interfaces. I will be happy to discuss my example, but please try to understand it first, as I already spent awhile preparing the example and its comments.
Here is the first of two files: Example.java
import java.util.*;
/**
* I hope this will demonstrate the polymorphic abilities gained
* by using interfaces in your Java programming. I don't know if
* this program does anything all that useful, well ...except for
* the steering functions of the duke toy that is.
*/
public class Example {
//
// This Vector will hold many different types of vehicle objects.
// By using an interface, we can perform generic operations on
// the collection without caring about the individual 'type' of
// each vehicle. We will be able to treat the collection as a whole.
private Vector vehicle_collection = new Vector();
//
// Simple method to add different vehicle types to our collection.
public void addVehicle(Object o) {
vehicle_collection.add(o);
}
//
// These methods show the whole polymorphic point to this example.
// We can iterate through all the different classes in the
// collection and, because they all implement Steerable, we
// can steer them without needing to know what exact type they
// are. All the program cares is that they have Steerable methods.
// We just cast them to our Steerable type.Too cool.
public void steerCollectionLeft() {
Iterator it = vehicle_collection.iterator();
while(it.hasNext()) {
((InterfaceExampleIF.Steerable)it.next()).goLeft();
}
}
//
public void steerCollectionRight() {
Iterator it = vehicle_collection.iterator();
while(it.hasNext()) {
((InterfaceExampleIF.Steerable)it.next()).goRight();
}
}
//
public void steerCollectionStraight() {
Iterator it = vehicle_collection.iterator();
while(it.hasNext()) {
// You can actually get an 'instance' of the objects interface like this.
// If you want to 'use' it for awhile, this might be better than casting.
//((InterfaceExampleIF.Steerable)it.next()).goStraight();
InterfaceExampleIF.Steerable steerable =
(InterfaceExampleIF.Steerable) it.next();
steerable.goStraight();
}
}
//
// Something sneaky here ...the abstract class! Its a very fine line indeed.
public void printCollectionDirections() {
Iterator it = vehicle_collection.iterator();
while(it.hasNext()) {
System.out.println(
((InterfaceExampleIF.SteerableThing)it.next()).getDirection()
);
}
}
/**
*
* Here, we just create a bunch of different 'types' of classes that
* all implement Steerable. We add them to our 'Example' collection,
* and then steer them all in unison without dealing with what type
* of vehicle each object actually is. Polymorphism is your buddy.
*/
public static void main( String[] args ) {
//
// Fire up our example vehicle collection and fill it.
Example example = new Example();
example.addVehicle(new InterfaceExampleIF.Car());
example.addVehicle(new InterfaceExampleIF.Boat());
example.addVehicle(new InterfaceExampleIF.Car());
example.addVehicle(new InterfaceExampleIF.Car());
example.addVehicle(new InterfaceExampleIF.Boat());
example.addVehicle(new InterfaceExampleIF.RemoteControlDuke());
//
// Show what direction each vehicle in the collection is going.
example.printCollectionDirections();
//
// Steer all the vehicles in the collection to the right.
example.steerCollectionRight();
example.printCollectionDirections();
//
// Steer all the vehicles in the collection straight.
example.steerCollectionStraight();
example.printCollectionDirections();
//
// Steer all the vehicles in the collection to the left.
example.steerCollectionLeft();
example.printCollectionDirections();
}
// done!
}
Here is the second of two files: InterfaceExampleIF.java
/**
* Right of the bat I have something really weird here. Don't get hung up on this
* first declaration of 'interface InterfaceExampleIF'. This is not relevant
* to my example about polymorphism ...it just shows yet another usage for an
* interface. I have created a namespace, much like a package does, inside of an
* interface declaration. I have placed all the classes I am going to use in my
* example inside of this namespace. It's a nice trick that avoids making many
* packages or many loose files. Keep in mind that the 'modeling' rules for this
* usage of the interface require the inside classes to relate very closely to one
* another, which my example may or may not do. Anyway, this is all beside the point.
* Just forget about this, and move to the inside and focus on the actual example.
* In other words, just treat this outer interface as if it were a package declaration.
*
*/
public interface InterfaceExampleIF {
/**
*
* Here is our first interface example.
* It holds some constants for our example, you've know doubt seen this?
*/
public interface SteerableStringConstants {
public final static String FORWARD = "straight";
public final static String LEFT= "left";
public final static String RIGHT= "right";
}
/**
*
* This will be our main example interface. It allows us to make anything
* steerable by simply adhering to the contract enforced by this interface.
* In other words, any class that inherits this ability must provide
* its own functionality to make these methods so, as Jean Luc Pickard
* would have said.
*/
public interface Steerable {
public void goStraight();
public void goLeft();
public void goRight();
}
/**
*
* This is an abstract class to encapsulate stuff common to all our
* different vehicle types. Notice that because it is abstract, it
* isn't required to implement the Steerable methods. Instead, it
* passes that requirement on down to any class that extends this one.
*/
public static abstract class SteerableThing implements Steerable,
SteerableStringConstants {
protected String direction = FORWARD;
public String getDirection() {
return direction;
}
}
/**
* This class defines a thing that can be steered called a car.
* Here we must provide the necessary code to make a car change directions.
*
* We might pivot tires here and apply a small drag to the cars velocity.
*/
public static class Car extends SteerableThing {
public void goStraight() { direction = "Car goes " + FORWARD; }
public void goLeft() { direction = "Car goes " + LEFT; }
public void goRight() { direction = "Car goes " + RIGHT; }
}
/**
* This class defines a thing that can be steered called a boat.
* Here we must provide the necessary code to make a boat change directions.
*
* We might turn the rudder in the opposite direction here and calculate
* how much the boat will list according to cargo levels in the hold.
*/
public static class Boat extends SteerableThing {
public void goStraight() { direction = "Boat goes " + FORWARD; }
public void goLeft() { direction = "Boat goes " + LEFT; }
public void goRight() { direction = "Boat goes " + RIGHT; }
}
/**
* This class defines a thing that can be steered called remote control duke.
* Here we must provide necessary code to make the duke toy change directions.
*
* We might look at the market closely here and determine how MS stock
* prices are affected each time duke moves to the left or to the right.
*/
public static class RemoteControlDuke extends SteerableThing {
public void goStraight() { direction = "RemoteControlDuke goes "+FORWARD; }
public void goLeft() { direction = "RemoteControlDuke goes " + LEFT; }
public void goRight() { direction = "RemoteControlDuke goes " + RIGHT; }
}
// done!
}
Good luck, I hope this example helped a little.
GumB.
#18; Wed, 18 Jul 2007 19:30:00 GMT

- Very Nice, I am not going to review it right now but I will later tonight.#19; Wed, 18 Jul 2007 19:30:00 GMT

An interface is extremely useful for using generic-programming. The methods that are implemented in various classes have a common return type or something that makes the different classes comparable in some way. I did a subject at uni and the lecturer was possibly the world's biggest fan of generic programming. At first my thoughts were "what the hell for" but after seeing it used in a project, i try and write as much stuff generically. I don't know, it seems to save A LOT of time once it has been designed well. Typical of good OO design :)
#20; Wed, 18 Jul 2007 19:30:00 GMT

> k here is a ?, lets say I don't implement runnable,
> lets say I just use the run method, could I still make
> a thread without implementing runnable? If not why
> not? Because what recognizes the run method if all
> your doing is implementing runnable?
it would not behave like a Thread, ie spawn a new process, running independently of other threads, instead the run() method would be aclled and where it was called from would wait untill run() returned rather than continuing with the code while the Runnable class executed according to Thread sheduling
the method run() in a class that implements Runnable (Thread does too) becomes important to the run time environment and performs the required tasks to get the new process running
BTW the documentaiotn recomends that a class that needs to be run as a Thread should use the interface rather than subclassing Thread if thats all you want it to do, since it is not proper (java) programming to subclass unless you want to change some behavior of the class
#21; Wed, 18 Jul 2007 19:30:00 GMT