Reputation: 21
I read the code below in a Java book. I understand that main class by default inherits Thread class so, currentThread(); instead of Thread.currentThread(); will also do the job.
But what I don't get is: What is Thread in Thread.currentThread(); or Thread.sleep();-- A class or an object? And can a class and its object have same name?
class Demo {
public static void main(String args[]) {
Thread t=Thread.currentThread();
t.setName("My Thread");
System.out.println("Current Thread: "+t);
try {
Thread.sleep(1000);
}
catch(InterruptedException e) {
System.out.println(e);
}
}
}
Upvotes: 0
Views: 870
Reputation: 116908
I understand that main class by default inherits Thread class so, currentThread(); instead of Thread.currentThread(); will also do the job.
No, this is not right. There is, by default, a "main" thread that runs the main
method but this doesn't "inherit" the thread class. Thread.currentThread()
is calling a java static
method. They are different.
What is Thread in Thread.currentThread(); or Thread.sleep();-- A class or an object?
Thread.currentThread()
and Thread.sleep()
are both static methods. See this tutorial on static methods. They are using the Thread
class. There is no instance object involved with these two calls.
Thread.currentThread()
returns an instance of the Thread
class which is the "main" thread running the main method. In your example, t
is an instance of the Thread
class. Again, check the tutorial and other Java docs on the difference between instance and static methods.
And can a class and its object have same name?
Unfortunately yes. This is the reason why uppercase and lowercase on field names is important to make it easier for you the programmer to see the difference.
// this compiles unfortunately
Thread Thread = Thread.currentThread();
// leading lowercase field names is a much better pattern
Thread thread = Thread.currentThread();
Upvotes: 5
Reputation: 21851
Thread
is the name of a class. currentThread()
and sleep()
are static methods of this class, that's why you're able to reference them without creating objects of the class.
You can write currentThread()
instead of Thread.currentThread()
only if you've performed static import of the Thread
class itself.
Upvotes: 1