tags:

views:

149

answers:

7

I realize that the method run() must be declared because its declared in the Runnable interface. But my question comes when this class runs how is the Thread object allowed if there is no import call to a particular package? how does runnable know anything about Thread or its methods? does the Runnable interface extend the Thread class? Obviously I don't understand interfaces very well. thanks in advance.

    class PrimeFinder implements Runnable{
         public long target;
         public long prime;
         public boolean finished = false;
         public Thread runner;
         PrimeFinder(long inTarget){
              target = inTarget;
              if(runner == null){
              runner = new Thread(this);
              runner.start()
         }
    }
    public void run(){

    }
}
+4  A: 

In this situation, I like to think of interfaces as contracts. By saying that your class implements Runnable, you are explicitly stating that your class adheres to the Runnable contract. This means that other code can create an instance of your class and assign to a Runnable type:

Runnable r = new PrimeFinder();

Further, by adhering to this contract you are guaranteeing that other code calling your class can expect to find the methods of Runnable implemented (in this case run() ).

darren
But whats the point of them if they dont actually do anything but force you to retype the method again in your class but now with actually code?
Karl Patrick
They do plenty. Consider the example of parsing XML in your application. You will find an interface to XML processing in the Java JDK (under javax.xml). You may wonder, what is the point of this interface? Well, any third party vendor can now come along and implement that interface (just as you are doing in your code above) and provide that as a product for other developers to use. The key point is that it does not matter that actual classes that third party has used for its solution, ONLY that it implements the XML interface defined in javax.xml.
darren
darren makes a really good point and it shouldn't be ignored - if you're just starting out, understanding this concept can really help you out. Check out http://www.javaworld.com/javaworld/jw-08-1999/jw-08-interfaces.html to also give you a bit of info on why interfaces are good stuff.
SB
okay, so if all these classes implement the same interface then by implementing the interface in your own class like my example. When i go to use thread, thread already knows it expects a "runnable" object even though that object can be anything? I think i am starting to get it. thank you for your help.
Karl Patrick
exactly. Your "real" class can be anything you like, but if you state that implements some interface, then it can also be that type as well. To drive the point home. You might have a class called Boy and a class called Girl, but if both of these classes implement the interface Loser, then you can do either Loser l = new Boy() or Loser l = new Girl(), and treat them both as losers.
darren
Thank you very much. I actually created your example with a boy and girl class implementing a loser interface just to actually see it work. I am a visual person and like to see it. This clears it all up for me. Thanks again :)
Karl Patrick
+1  A: 

This has nothing to do with interfaces. Rather, Thread is in the java.lang package and since java.lang is the default package, you don't need to import it. That is, java.lang.* is imported by default, so you don't need to explicitly import it yourself.

bingle
I dont understand interfaces. this is just an example of one that i dont understand. I dont see how an interface is useful at all if it only declares the methods without the body.
Karl Patrick
There are actually two issues to your original question: (1) Why don't I need an import statement to use Thread and (2) what's the use of interfaces. The first one is easy and I answered. The second one is a book unto itself. I would recommend searching for an answer on SO or looking for articles elsewhere.
bingle
+2  A: 

Yes, Thread implements Runnable.

As the API references states runnable interface is designed to provide a common protocol for objects that wish to execute code while they are active.

You are getting confused because there are two ways of making this kind of concurrency in Java:

  • you can extend a Thread class overriding the default run method, then invoke the thread in a way similar to new MyThread().start()
  • you can write a class that implements the Runnable interface and start it in a similar way: new Thread(new MyRunnable()).start()

These approaches are IDENTICAL. Infact the run method of class Thread normally calls the run method of Runnable object attached to the thread if any, otherwise it returns.

What is the need of having a Runnable interface? It's useful because it declares a protocol to let classes be considered with specific characteristics.

This is the same thing of Comparable interface or Serializable interface, but here you effectively have a method to override (public void run()) while for example Serializable is just a trait you give to your class.

A final example is the fact that TimerTask implements Runnable. TimerTask is used together with Timer class to execute delayed or periodic tasks, so it makes sense that a timertask is also runnable, so that Timer can launch tasks using exactly that method.

EDIT: since you seem confused by the usefulness of an interface you have to think that: Java is a statically typed language. What does it mean? It means that it needs to know everything about a type during compilation to be able to guarantee that not run-time type error will ever be thrown.

Ok, now suppose that Java API supports a hipotetically class to draw shapes. So you can write your own classes for the shapes and then feed them to this class (let's call it ShapeDrawer).

ShapeDrawer needs to know how to draw the shapes you pass to it and the only way to be sure of it is to decide that every Shape object must have a method called public void drawMe(), so that ShapeDrawer can call this method on every Shape you attach to it without knowing anything more than this.

So you declare an interface

public interface Shape
{
  public void drawMe();
}

that classes can use to be considered a Shape. And if a class is a Shape you can pass it to your ShapeDrawer class with no problem:

class ShapeDrawer
{
  public void addShape(Shape shape) { ... }
  public void drawShapes()
  {
    for (Shape s : shapes)
      s.drawMe();
  }
}

So that compiler is happy because when adding shapes you add classes that implements Shape, you class knows exactly how to draw such shapes and developers are happy because you separated the common protocol of an object from their specific implementations.

It's a sort of contract, if you want a Triangle class that is able to be drawn by ShapeManager you have to the declare that method, so that you can call for example

shapeDrawerInstance.addShape(new Triangle())

Jack
+3  A: 

Nope. Thread is in lava.lang package, so it's implicity imported.

And: Thread knows Runnable.

That's why Thread receives an Runnable (this implements Runnable) and calls its method run() inside its own thread of execution.

The Thread mantains a reference to the Runnable you implement:

public Thread(Runnable runnable) {
   this.myRunnable = runnable;
}

private Runnable myRunnable;

The start method of Thread class could look like:

public void start() {
  // do weird stuff to create my own execution and...
  myRunnable.run();
}
helios
A: 

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runnable.html

Thread implements Runnable. Thread is in java.lang.* and therefore doesn't need to be imported, as it is imported automatically.

powerj1984
See my comment. Thread is in java.lang which is imported by default.
bingle
A: 

Your code the way it's written doesn't compile. You declared PrimeFinder implements Runnable, but it doesn't actually @Override public void run().

As for why interfaces are useful, it's because they define types that you can work with regardless of implementations. If you work with a Closeable, for example, you know you can close() it. The actual class may be any of the many that implements it (see full list), but working with the interface allows you to step back and just say that they're all Closeable.

With interfaces, you don't inherit implementation; you inherit a TYPE. If there's another code that works with Closeable types (for example, all it does is invoke close() on them with exception checking), then you can pass it anything that implements Closeable. In fact, this "please close this thing for me, okay thanks" utility method already exists, and it's very flexible and highly reusable since it works with the interface.

By using interfaces instead of specific implementation classes, you encapsulate your logic much more cleanly. An algorithm that works with a Set interface, for example, doesn't care if it's actually a TreeSet or a HashSet. This lack of dependency is a good thing, because it allows the algorithm to be very flexible -- it can also work with a SuperMagicalSet implements Set in the future, for example.

Working with interfaces also ensures proper encapsulation, because not knowing what the actual implementation class will be, you must work only with what the interface provides.

I recommend reading Josh Bloch's Effective Java 2nd Edition:

  • Item 18: Prefer interfaces to abstract classes
  • Item 19: Use interfaces to define types
polygenelubricants
Its not meant to compile. My question is because i dont understand interfaces at all and i was using this snippet as an example. But i am getting some good feed back in a very short time. My real question i guess is why use interfaces if they only declare the method without any body or code? whats the point?
Karl Patrick
I just added something to try to address that.
polygenelubricants
I just looked at the list. So close(), when implemented, you have to define how the object is closed. For example, the StringReader class implements Closable and it then defines how to close the StringReader object within its own class. Why is the interface of any use here if you have to define the code anyways?
Karl Patrick
With interfaces, you don't inherit implementation; you inherit a TYPE. If there's _another_ code that works with `Closeable` types (for example, all it does is invoke `close()` on them with exception checking), then you can pass your `StringReader` to that class, or anything else that `implements Closeable`. In fact, this "please close this thing for me, okay thanks" utility method already exists, and it's very flexible and highly reusable since it works with the interface.
polygenelubricants
okay, so if all these classes implement the same interface then by implementing the interface in your own class like my example. When i go to use thread, thread already knows it expects a "runnable" object even though that object can be anything? I think i am starting to get it. thank you for your help.
Karl Patrick
A: 

The class Thread implements Runnable. Runnable does not know anything about Thread, but Thread knows everything about Runnable.

Other classes that use Thread know that Thread implements the interface specified in Runnable.

Vladislav