What is an interface?

B

billreyn

Someone please help me out, I've looked at 50+ books on Interfaces.
I understand contracts etc. But how on earth does an Interface method
do something like start a thread running? eg:

class TryThreads implements Runnable
{
public void run() {
for (int x = 1; x < 100; x++) { // runs a new thread
} }

Above is MY implementation of the Interface method run() (its not
exactly right, no matter), and it will run in its own thread. But I
have not written anything to do with running a thread, so how does it
'know' to do this special task? (running a thread)??? All I do is my
OWN implementation of run() which is just a 'for' loop. How does it
'know' to run it in its own thread?? According to every book I have
read, an Interface only forces me to write my own method with the
method name & params that is in the Interface. hat I understand, so how
does it run a thread? Its not in my implementation.

Will some kind person explain whats going on in simple English that
even I could understand.
 
C

Chris Smith

class TryThreads implements Runnable
{
public void run() {
for (int x = 1; x < 100; x++) { // runs a new thread
} }

Above is MY implementation of the Interface method run() (its not
exactly right, no matter), and it will run in its own thread. But I
have not written anything to do with running a thread, so how does it
'know' to do this special task? (running a thread)???

It doesn't. The Runnable interface means exactly what it says:
something that can be run. For example, if I take your code and write:

TryThreads tt = new TryThreads();
tt.run();

This will *NOT* start a new thread. It will just run that for loop, in
same thread that I used to call the method. There are also standard API
interfaces that use Runnable instances to represent things that won't
necessarily happen in a new Thread.

You're probably thinking of the following code:

TryThreads tt = new TryThreads();
Thread t = new Thread(tt);
t.start();

This will start a new thread, and run the for loop in the new thread.
However, the code to start a new thread isn't in your TryThreads class;
it's in the standard API class java.lang.Thread. The standard API
thread class just uses a Runnable instance to represent the code that
the new thread will run.

Note that Runnable is really just a convention for encapsulating
something that can be run. There are several other uses of Runnable
besides starting a new Thread. For example, there is AWT's
EventQueue.invokeLater, which schedules a task to be run at a later time
in the AWT event dispatch thread rather than a new thread. An even
better example is Java 1.5's java.util.concurrent.Executor, if you're
working with that version.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
B

billreyn

Thanks for the reply Chris, but I am still no nearer an understanding
because I cannot see anything that Runnable has to do with threads
whatsoever. The runnable Interface has in it is a naked run(*) method
and nothing else in it. So why should it do anything at all with
threads?

I am missing some basic point somewhere and have been for 3 years!
 
D

Daniel Dyer

Thanks for the reply Chris, but I am still no nearer an understanding
because I cannot see anything that Runnable has to do with threads
whatsoever. The runnable Interface has in it is a naked run(*) method
and nothing else in it. So why should it do anything at all with
threads?

I am missing some basic point somewhere and have been for 3 years!

That's because there is nothing in the Runnable interface that is
connected in any way with threads. Runnable is just a way of describing
some block of computation/piece of work that can be performed, it has
nothing to do with threads. All it says is that any object that claims to
implement Runnable will always have a method called run that will perform
some unspecified work. If you call run whatever logic is in the run
method gets executed and that's it. It really is as simple as it looks.

The Thread class however is more complicated. It depends on Runnable even
though Runnable knows nothing of threads. All the magic involved in
spawning threads is hidden away in the Thread class. The only reason
threads use Runnable is because a thread needs be provided with some work
to perform and that work is encapsulated in the run method of a Runnable
object.

Dan.
 
B

billreyn

I still can't see what 'Runnable' gets you if it has no connection to
the Threads class, why use it at all? There must be some message passed
for it to make any sense?

This program creates a new thread and start() calls run(). Why? There's
no connection. Whats the Interface doing - is it that the Thread object
looks for a method called run()? In which case why not just have a
method called run() with no Runnable Interface, that should work too
(but it doesn't)?


import java.io.*;
class TryThreads implements Runnable
{
public void run() {
for (int x = 1; x < 100; x++) { // runs a new thread called
'Fred'
System.out.println("I am thread: " +
Thread.currentThread().getName());
}
}
public void tester() {
System.out.println("I am not thread Fred but I am thread "
+ Thread.currentThread().getName());
}
public void tester2() {
System.out.println("I am also not thread Fred but I am
thread " + Thread.currentThread().getName());
}
}
class DriveThreads {
public static void main(String [] args ) {
TryThreads tr = new TryThreads();
Thread t = new Thread(tr); // t is a new thread called 'Fred'
t.setName("Fred");
t.start(); // calls 'run' method in TryThreads class
for (int x = 1; x < 100; x++) {
System.out.println("I am an ordinary 'for' loop in thread
" + Thread.currentThread().getName() );
}
tr.tester();
tr.tester2(); }
}

OUTPUT
Creates a thread called Fred and the normal thread called main
continues to run also.
 
M

Mike Schilling

Someone please help me out, I've looked at 50+ books on Interfaces.
I understand contracts etc. But how on earth does an Interface method
do something like start a thread running? eg:

class TryThreads implements Runnable
{
public void run() {
for (int x = 1; x < 100; x++) { // runs a new thread
} }

Above is MY implementation of the Interface method run() (its not
exactly right, no matter), and it will run in its own thread. But I
have not written anything to do with running a thread, so how does it
'know' to do this special task? (running a thread)??? All I do is my
OWN implementation of run() which is just a 'for' loop. How does it
'know' to run it in its own thread?? According to every book I have
read, an Interface only forces me to write my own method with the
method name & params that is in the Interface. hat I understand, so how
does it run a thread? Its not in my implementation.

Will some kind person explain whats going on in simple English that
even I could understand.

This is very similar to asking "What does compareTo() have to do with
sorting lists?" The answer is that the sort algorithm can be written
generically by factoring out how to compare different sorts of objects. If
you mandate that an object implement the compareTo method, by insisting that
it implement Comparable, than you can write a sort algorithm that contains
the fragment:

// compare the two objects
if (a.compareTo(b) < 0) {
// switch them
}

Likewise, the low-level Java code that starts a new thread looks (very
loosely) like:

void startThread(Runnable r) {
// do magic to create a new stack
// do magic to switch to the new stack
r.run()
}

That is, after creating the new thread in some JVM-specific manner, it calls
Runnable.run() to run in that thread, and run() is used as a callback, just
as compareTo() is above. Since implementing an interface means implementing
methods with given signatures, one of their main uses is to specify that a
given callback is available.
 
M

Mike Schilling

I still can't see what 'Runnable' gets you if it has no connection to
the Threads class, why use it at all? There must be some message passed
for it to make any sense?

This program creates a new thread and start() calls run(). Why? There's
no connection. Whats the Interface doing - is it that the Thread object
looks for a method called run()? In which case why not just have a
method called run() with no Runnable Interface, that should work too
(but it doesn't)?

For one thing, requiring the interface allows a normal compile-time check
that run() is defined. If C1 implements Runnable, it has a public method
name Run() with no arguments.
 
R

Roedy Green

Someone please help me out, I've looked at 50+ books on Interfaces.
I understand contracts etc. But how on earth does an Interface method
do something like start a thread running? eg:

see http://mindprod.com/jgloss/interface.html
and follow the links.

An interface Object does not exist. However an interface reference to
a real object that implements the interface can do any of its methods
the interface exposes, but not the rest.

--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm

Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
 
C

Chris Head

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

I still can't see what 'Runnable' gets you if it has no connection to
the Threads class, why use it at all? There must be some message passed
for it to make any sense?

This program creates a new thread and start() calls run(). Why? There's
no connection. Whats the Interface doing - is it that the Thread object
looks for a method called run()? In which case why not just have a
method called run() with no Runnable Interface, that should work too
(but it doesn't)?
[snip]

Hi,
Why use it? You say yourself in an earlier post that you understand the
"contract" idea: this is EXACTLY what's going on here.

When we construct a new thread (an instance of java.lang.Thread), how do
we tell it what code to run once it starts? In C, we would pass a
pointer to a function to our thread library. In Java, there are no
pointers to methods, so we use an instance of a class instead. The
specification for java.lang.Thread says that the new thread will invoke
run() on the given object. Thus, by defining run(), you are defining
what work the thread will do. You ask, "why do we need the Runnable
interface"? Here's why: imagine that the java.lang.Thread constructor
accepted an Object instead of a Runnable. In this case, you could pass
in an object whose class didn't contain a run() method. What should the
thread do when you call start() now? Explode? Throw an exception?
Throwing an exception would be the sensible thing to do. However, this
leads to our next problem: the exception is thrown at runtime. The
java.lang.Thread class must check, at runtime, whether or not your class
contains a run() method. This takes a bit of CPU time, it takes a bit of
time out of the Sun programmers' lives, and it also means you won't
notice that your run() method is missing until runtime (you won't find
out at compile time). In contrast, by using a Runnable, there's no way
you can possibly pass in an object which doesn't contain a run() method.
The presence of the method is absolutely guaranteed. If you misspell it
an type Run() instead of run(), for example, you'll be informed of the
fact by the compiler. You won't have to wait until your program runs.
Better still, maybe the thread gets started only one in a million times.
Do you want to have to start your program a million times to discover a
spelling mistake? (before anyone jumps on me and says that you should be
testing the thread's functionality anyway, I agree: without compile-time
checking, you'd have to start your program a million times to find the
spelling mistake, fix it, recompile, and then start it ANOTHER million
times to check the function's behaviour)

Sorry for rambling. Anyway, it's just the contract idea. If a Thread is
going to fulfil its contract to you and run code you specify in a
separate thread, you must fulfil your contract to the Thread by
providing the code to run in the proper format. That's a Runnable.

Chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)

iD8DBQFCy3TxgxSrXuMbw1YRAgGrAKCBEhLrG1Xim0dC42kFq874Pae31QCfawfK
QDN3+6bp9IdjE2elToguKBY=
=zTIQ
-----END PGP SIGNATURE-----
 
B

billreyn

'run() is used as a callback' this is the magic explanation that I have
never understood or even seen in my 50 books.This is beginning to sound
rational at long long long last. Why don't books mention 'callbacks' in
Interfaces? It simply does not make sense without that (in my small
mind). They only ever discuss 'contracts' which I understand
completely.
I am not exactly sure of the callback process, but will start
investigating them (delegates etc) and hopefully will understand
completely then. Its got something to do with what calls what and what
is 'passed' to what.
I shall also look at compareTo()
 
T

Thomas Weidenfeller

Someone please help me out, I've looked at 50+ books on Interfaces.
I understand contracts etc. But how on earth does an Interface method
do something like start a thread running? eg:

class TryThreads implements Runnable
{
public void run() {
for (int x = 1; x < 100; x++) { // runs a new thread

No, it doesn't. It CAN run in a thread - if you tell a thread to do so.
It doesn't do it by its own.
} }

Above is MY implementation of the Interface method run() (its not
exactly right, no matter), and it will run in its own thread.

Only when you tell a thread to do this.
But I
have not written anything to do with running a thread, so how does it
'know' to do this special task? (running a thread)???

It doesn't. You have to tell a thread to run it.
All I do is my
OWN implementation of run() which is just a 'for' loop. How does it
'know' to run it in its own thread??

It doesn't. Didn't I say this before? :)

According to every book I have
read, an Interface only forces me to write my own method with the
method name & params that is in the Interface. hat I understand, so how
does it run a thread?

It doesn't. Didn't I ... :))
Its not in my implementation.

Will some kind person explain whats going on in simple English that
even I could understand.

A runnable represents a piece of code which can be run by someone.
Whoever wants to run that piece of code can run it by calling the run()
method.

You can run it yourself by calling the run() method.

If you tell no one to run it, it will not run.

If you tell a thread to run it (in parallel to your current thread), the
thread will run it by calling the run() method of the runnable:

Runnable codeToRun = new TryThreads();
Thread aThread = new Thread(codeToRun);
aThread.start(); // runs the code in a separate thread

"new Thread(codeToRun)" creates a new thread object, which is not
running at this point. But which already knows that the thread, when
started, should run the code in "codeToRun". The call to start() indeed
starts the thread, which will do what it has been told: run the
"codeToRun", by calling codeToRun.run().


/Thomas
 
C

Chris Uppal

'run() is used as a callback' this is the magic explanation that I have
never understood or even seen in my 50 books.This is beginning to sound
rational at long long long last. Why don't books mention 'callbacks' in
Interfaces? It simply does not make sense without that (in my small
mind). They only ever discuss 'contracts' which I understand
completely.

Probably because interfaces and callbacks are completely separate beasts.

However there /is/ a connection of sorts. If you have some object, and you
want to invoke one of its methods, then you have to know that that method
exists. A callback is just a special case of invoking a method (there's no
formal difference, it's just that some methods are used as callbacks, some are
not). So, for the Java runtime machinery to issue the callback method run(),
it has to be sure that he method exists. That's where interfaces come in. The
interface is (among other things) a contract defining what methods the caller
can expect to find. The specific interface java.lang.Runnable, represents the
contract that any object that implements that interface will have a void run()
method. So, when you start a thread you (normally) provide an object that
implements java.lang.Runnable (which is checked by the compiler, and by the
runtime), so the system knows that it can safely invoke that object's run()
callback method as the body of the new thread.

-- chris
 
?

.

Someone please help me out, I've looked at 50+ books on Interfaces.
I understand contracts etc. But how on earth does an Interface method
do something like start a thread running? eg:

You are mixing two things here. An interface is just a way of listing the
methods you want someone to create. For example, if your class implements
the Runnable interface you are required to have a public method called run
that takes no inputs and returns void. If you implement this interface you
have not created a thread. The creating of a Thread is something
COMPLETELY seperate.
class TryThreads implements Runnable
{
public void run() {
for (int x = 1; x < 100; x++) { // runs a new thread
} }

The above class implements the interface Runnable. This does not make it a
Thread. I might create a project that requires a type called NotAThread.
My code is going to assume that the class NotAThread will have a method
called run that takes no inputs and returns void. Rather than create an
interface to enforce this requirement I see that there is an interface
called Runnable so I just use that. My project has nothing to do with
Thread but I can still use the Runnable interface.
Above is MY implementation of the Interface method run() (its not
exactly right, no matter), and it will run in its own thread.

Incorrect. Your above call has little to do with threads. On its own it
cannot run as a thread. All the magic to do that is in the Thread class.
The interface Runnable determines WHAT will become a thread. It does not
determine HOW something will become a thread.
But I have not written anything to do with running a thread, so how does
it 'know' to do this special task? (running a thread)??? All I do is my
OWN implementation of run() which is just a 'for' loop. How does it
'know' to run it in its own thread?? According to every book I have
read, an Interface only forces me to write my own method with the method
name & params that is in the Interface. hat I understand, so how does it
run a thread? Its not in my implementation.

Will some kind person explain whats going on in simple English that
even I could understand.

What you really want to understand is not interfaces but Thread.

You can create a thread by passing Thread a class that implements
Runnable.

The interface Runnable is just a contract between Thread and your class
promising that you have created a method called run that requires no
inputs and returns void. What Thread does with that method is the magic
that is threads.

The interface Runnable tells us WHAT method is going to be turned into a
thread. It does not tell us HOW it is turned into a thread.

Interfaces tell us WHAT methods are needed. It is a completely seperate
issue as to WHY those methods are needed and HOW they will be used.
 
B

billreyn

Thanks Thomas, its slowly starting to make sense. Its at the limits of
my intelligence though.
 
G

George Cherry

Chris Uppal said:
Probably because interfaces and callbacks are completely separate beasts.

However there /is/ a connection of sorts. If you have some object, and
you
want to invoke one of its methods, then you have to know that that method
exists. A callback is just a special case of invoking a method (there's
no
formal difference, it's just that some methods are used as callbacks, some
are
not). So, for the Java runtime machinery to issue the callback method
run(),
it has to be sure that he method exists. That's where interfaces come in.
The
interface is (among other things) a contract defining what methods the
caller
can expect to find. The specific interface java.lang.Runnable, represents
the
contract that any object that implements that interface will have a void
run()
method. So, when you start a thread you (normally) provide an object that
implements java.lang.Runnable (which is checked by the compiler, and by
the
runtime), so the system knows that it can safely invoke that object's
run()
callback method as the body of the new thread.

Yes. Maybe this will also help the op: A Thread is
a worker; the run() method in an instance of type
Runnable defines the work or task that the worker
Thread performs. The run() method gives the job
(task) description for the worker Thread. Also, the
Runnable interface is a more flexible and versatile
way to define the work than subclassing Thread
in a class that defines run()--since Java has only
single inheritance for implementations.

George W. Cherry
 
D

Dale King

I still can't see what 'Runnable' gets you if it has no connection to
the Threads class, why use it at all? There must be some message passed
for it to make any sense?

This program creates a new thread and start() calls run(). Why? There's
no connection.

Yes, there is a connection. That connection does not come from the
Runnable interface itself. The connection is in this code:
TryThreads tr = new TryThreads();
Thread t = new Thread(tr); // t is a new thread called 'Fred'

You created a new thread and "connected" it to the TtyThreads instance.
The thread object you created saves the reference to the Runnable
instance in a field of the thread object.

When you invoke start() it creates a new thread which then gets the
reference to the Runnable instance and invokes its run method.
Whats the Interface doing - is it that the Thread object
looks for a method called run()? In which case why not just have a
method called run() with no Runnable Interface, that should work too
(but it doesn't)?

But there is no way in Java to reference a method except for reflection.
If you want to point to something else that something else has to be an
object.

Interfaces are somewhat like a function pointer, but it allows you to
point to a whole set of functions not just one.

I could confuse the matter further by telling you that you can also
subclass Thread and put your run method in the subclass. This only works
because, in a very bad design decision on Sun's part, Thread itself
implements Runnable and the no-arg constructor stores a reference to
itself. I recommend against this approach however.
 
A

Andrew McDonagh

Dale said:
(e-mail address removed) wrote:


Interfaces are somewhat like a function pointer, but it allows you to
point to a whole set of functions not just one.

Interfaces are nothing like a function pointer.

They are a Type-ing mechanism, much like a C++ pure abstract class, only
with greater restrictions with which they can contain.

Andrew
 
M

Mike Schilling

Andrew McDonagh said:
Interfaces are nothing like a function pointer.

They are a Type-ing mechanism, much like a C++ pure abstract class, only
with greater restrictions with which they can contain.

An interface in Java is a contract to implement a set of method signatures,
nothing more and nothing less.
 
S

Stefan Ram

Mike Schilling said:
An interface in Java is a contract to implement a set of method
signatures, nothing more and nothing less.

It is a (reference type) specification, which might be used in
a declaration, instanceof, or cast expression.

A contract is an act resulting from the corresponding
declaration of two parties. What would correspond to such a
declaration would not be the interface( specification), but
the "implements" clause of a class declaration. This alone is
not a declaration from two parties, but from a single party.

Then, a reference expression might be written, which has an
interface type, which then indeed comes close to a kind of
contract between a class and a client.
 
A

Andrew McDonagh

Mike said:
An interface in Java is a contract to implement a set of method signatures,
nothing more and nothing less.

I think you are taking a simplistic meaning from what is a woolly
training wording of 'interfaces as contracts to implement' .

Yes, a class implementing an Interface is bound to either implement or
mark as abstract the method signatures defined within the interface.
However they are first and foremost a typing mechanism.

If it wasn't a type specification, how could we pass objects around as
either their direct class type OR the interface they implement?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top