aj983
aj983

Reputation: 293

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.

Upvotes: 0

Views: 55

Answers (3)

wrschneider
wrschneider

Reputation: 18780

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

Upvotes: 3

Alvin Baena
Alvin Baena

Reputation: 903

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.

Upvotes: 0

Yann Ramin
Yann Ramin

Reputation: 33187

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.

Upvotes: 3

Related Questions