if we create Thread object - Thread t1=new Thread(); does it actually mean we have created instance of class Thread, from which we can staticly call methods? (e.g sleep()).
When you call a static method, you do not call it from the object. That's why it's static. There is no need for an instance to execute a static method.
Example
Thread t1 = new Thread();
t1.checkAccess(); // <--- This is an instance method.
Thread.activeCount(); // <-- This is a static method.
When you see the new
keyword, it means that a new object is being created. In this case, it was an instance of class Thread
, as you quite rightly said.
How do you tell them apart?
Well, it's simple. If it's an instance method, it will be called from the context of an object.
String str = new String("hello");
str = str.replaceAll("o", "");
As you can see, you have to create an instance to use an instance method.
With a static method, it's even easier. They will be called with nothing but the name of the class.
String.copyValueOf(new char[] {'a', 'b', 'c'});
There is no need to create a new String
instance. Simply use the name of the class.
NOTE: As pointed out in the comments, a static method can be called from an instance object, but this isn't common practice. If you're ever unsure, documentation is your best friend. Or you can simply test by trying to call the same method from a static context.
When to use a static method instead of an instance method ?
Well this is answered, very well, here: Java: when to use static methods and I see no sense in repeating it :)