Java Runnable Question - java

I'm currently taking a course in Java and I've run into some confusing code.
Example:
Runnable runnable = new Runnable()
{
public void run()
{
//doStuff
}
};
I don't really get what this code is doing.
How can the run method be associated with an instance of a class?
I googled "Runnable" and found out that it is an interface. Am I implementing the interface by declaring the run method between curly brackets ? Can this be done for any interface in java ?
I could use some links/explanations. Thank you!

It's an anonymous inner class that's implementing the interface Runnable. Yes, you can implement any interface this way, although there are reasons why you would or wouldn't in any given case (lack of reusability being a big one in the "wouldn't" column). More about anonymous classes here, but it's basically a convenient form of this:
// Define it
class Foo implements Runnable
{
public void run()
{
// Do stuff
}
}
// And then use it
Runnable runnable = new Foo();
...provided Foo is an inner (or "nested") class. More about nested classes here.

yes, you are implementing the interface by declaring the run. Yes it can be done for any interface.
This is typically done when you pass an implementation to a method that expects an argument of an Interface type, and you don't have a declared class that is appropriate. You can just implement the interface on the spot, and that code runs. Pretty neat.

I googled "Runnable" and found out
that it is an interface. Am I
implementing the interface by
declaring the run method between curly
brackets ? Can this be done for any
interface in java ?
Yes!
This code is instantiating an object which implements Runnable. Because we can't actually construct an interface, any code which attempts to do so must provide implementations for the interface's methods in curly brackets. We don't really get to see what class Java is creating to implement Runnable (these are abstract terms).
If you were to do the following:
Runnable runnable = new Runnable()
{
public void run()
{
System.out.println("I'm running");
}
};
runnable.run();
you would see "I'm running" as your output.

In some situation , this sample code will be useful .... test runna = new test()
class test implements Runnable{
test(){
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("asd");
}
}
}

Related

Nested Functions - Processing

Can you build nested functions in Processing (Java?)
This code doesn't work. The compiler reads: unexpected token: void.
void keyPressed() {
if(click1 = true) {
graph();
}
if(click2= true) {
points();
}
void graph() {
....
....
}
}
You can't have nested functions. You can have anonymous classes, for example in a new thread:
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// This is all in an anonymous Runnable class.
}
});
Like others have said: no, you can't have "local functions" like that.
You also aren't doing your boolean comparison correctly, as a single = is assignment, not comparison. It should be either:
if(click1 == true) {
Or since you're already working with booleans, you can refer to it directly:
if(click1) {
Anyway, back to your question: you can't do what you're talking about, but you can get around it by using an anonymous class. To use an anonymous class, you need to have an existing class that you want to extend by overriding one or more of its functions, which you can do inside a method.
For example, we have the Runnable interface that we can implement by defining an anonymous class that defines the run() method, and then call that anonymous class directly. It looks like this:
void keyPressed() {
if(click1) {
new Runnable(){
public void run(){
//do graph stuff here
}
}.run();
}
if(click2) {
new Runnable(){
public void run(){
//do points stuff here
}
}.run();
}
}
More info on anonymous inner classes here: http://staticvoidgames.com/tutorials/objects/advancedInheritance
However, all of this has a pretty bad code smell, and isn't the way any sane person would do this. Why do you think you need a local method? Chances are you should either use separate classes, or a regular old top-level method.

Saving blocks of code in variables

In Objective C you have a function blocks.
You can save blocks of code in a variable and pass them as parameters.
[objects enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// Enumerating all the objects of an array
}];
In my game I have a MenuScene with MenuSceneItems.
In this case I would want to pass the code they should execute if they have been clicked.
This would eliminate the need of a switch statement.
Is there a way to to is there a way to do this or something similar in Java?
In Java you can't have anonymous function blocks you need to use an anonymous class:
menuScene.executeWhenClicked(new Runnable() {
public void run() {
// do something
}
});
This sounds like straightforward polymorphism e.g.
public interface Action {
void doSomethingWhenPressed();
}
and just implement an object that implements the above interface. Pass that as an argument.
You'd likely do this using an anonymous class e.g.
// this method takes an 'Action' as an argument
passToMethod(new Action() {
public void doSomethingWhenPressed() {
System.out.println("Pressed!");
}
});
In java, you create an object (it doesn't have to have an explicit class type) that extends Runnable, and put the block of code in the run method. Like so
Runnable myDelayedBlockOfCode = new Runnable() {
public void run() {
doA();
doB();
doC();
}
};
If working with a framework, look closer for a framework specific interface that allows you to place such blocks of code into whatever the framework will call.

Unable to understand declaration

I have a code snippet as
public class ThreadStates {
private static Thread t1 = new Thread("T1") {
public void run() {
try {
sleep(2);
for (int i = 100; i > 0; i--) ;
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
.......And rest of code follows.
What type of declation is step 1. I can see that we have no inherited Thread class in ThreadStates class, then why run() method declaration is coming. PLease clarify what is happening.
You have created an anonymous inner class which inherits from Thread (note the { directly following new Thread(). You are giving this class a run method, and storing it in t1.
It's called an anonymous inner class. When you say 'new Thread("T1") { ... }', you're effectively defining a new subclass of Thread.
Is this a variation of an anonymous inner class?
http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
When you call a class that directly implements the Runnable class, you immediately inherit all the methods that said class does. Thread is one of the classes that implements Runnable and it makes you implement the run()method which is an abstract one.
That's why it shows the run()nethod there.

Declaring Anonymous Inner class

rb.addActionListener(new ActionEvent(ae) {
public void actionPerformed(ActionEvent ae) {
nowCall(ae);
}
});
Another way
Thread th=new Thread(Runnable r) {
public void run() {
// do something
}
};
// notice the ending of above 2 snippets
I am really confused seeing these two.It seems there is no exact pattern to declare an anonymous inner class.
please explain the syntax for anonymous inner class.
The second isn't valid, as far as I can see and test.
What would be more common would be to create a new Runnable implementation:
Thread th=new Thread(new Runnable() {
#Override
public void run() {
// This implements Runnable.run
}
});
Now you could just override the run method of a normal thread:
Thread th=new Thread() {
#Override
public void run() {
// This overrides Thread.run
}
};
... but personally I prefer specifying the Runnable separately when creating a thread.
Now the difference that you noticed at the end is simply whether the expression is used as an argument (e.g. to the addActionListener method or the Thread(Runnable) constructor, or whether it's just assigned directly to the variable. Think of the whole new TypeName() { ... } as a single expression, and it's just the difference between:
Thread th = expression;
and
Thread th = new Runnable(expression);
There is the difference that in the first case your passing it as an parameter to a method and in the second example you're storing it in a local variable.
So you can't really compare both examples against each other.
[...] notice the ending of above 2 snippets
The trailing ) in your first example is simply a termination of
rb.addActionListener(
(i.e., your two examples have different endings because one is a right hand side of an assignment
Thread th = ... ;
and the other is an argument to a method call
...addActionListener( ... );
The syntax of creating an anonymous class is simply:
new SomeClassOrInterface() {
// implementation goes here
}
Which as you can see is the pattern for both of your examples.
From Anonymous Classes (Java in a Nutshell):
3.12.3. New Syntax for Anonymous Classes
We've already seen examples of the syntax for defining and instantiating an anonymous class. We can express that syntax more formally as:
new class-name ( [ argument-list ] ) { class-body }
or:
new interface-name () { class-body }
Also, you have a typo in your second example. It should probably read new Thread() { ... or new Thread(r) { ... (though in the latter case the overridden method will not be called).
Instanciating new anonymous class and passing the object to addActionListener method.
Instanciating new anonymous class and assigning the object to local variable th
They are both the same. You put the anonymous class right after the declaration, before the semicolons:
new ActionEvent(ae) {class details, methods etc} ;
and
Thread(Runnable r) { public void run() { // do something }} ;
in both cases you create a new instance of the class, in the first example you use it as a parameter to method, and in the second you assign it to a variable.
The difference is that you can either implement an interface as an anonymous inner class or extend a class. In you example both are extending a class

Java, alert parent on object change

I have the following setup in Java,
public class Main {
// starts sub class
SubClass sub = new SubClass();
sub.start();
// sub will keep running and call method alert() on a specif change
// method alert is void but updates a public variable named status on sub
while(1==1) {
// I should ideally be able to catch/read sub status result here
// how can I do it?
}
}
I'm new to Java so this may not be valid and my approach may be wrong. That being the case please point me in the right direction.
Thank you.
I presume SubClass.start() starts a new thread so the parent runs in parallel with the child. Then the main class can do a Object.wait() on the sub object, and the SubClass thread can do a Object.notify() on the sub object.
you should start by putting your code into a main method :)
If your SubClass is not already a Runnable,
public class Main
{
public static void main(String args[])
{
Thread myThread = new Thread(new Runnable()
{
public void run()
{
//Instantiate your SubClass here and do stuff. You can pass yourself as a parameter if you plan to do callbacks.
}
});
myThread.setDaemon(true);
myThread.start();
}
}
Alternatively if you've implemented the Runnable interface on SubClass then just use the thread mechanics (wait(), notify(), etc etc).

Categories