Static method

Why to call static methods using class name though we can call static method by using object also....?
[109 byte] By [prady_joa] at [2007-11-26 18:55:08]
# 1
> Why to call static methods using class name though we> can call static method by using object also....?Because you don't always have an object and calling a static method through an instance reference is legal but bad style.
CeciNEstPasUnProgrammeura at 2007-7-9 20:33:04 > top of Java-index,Java Essentials,Java Programming...
# 2

If you can call a static method through the class name, it means that you don't have to create an instance of the object to call the method. For example, calling an instance of java.lang.Math just to use it's methods (all of which are static) is more cumbersome and unneccesary.

Also, it's "more natural" to not have to create an instance of a class to call methods that are static.

Being able to call static methods through a handle is just a convenience.

Message was edited by:

Dross

Drossa at 2007-7-9 20:33:04 > top of Java-index,Java Essentials,Java Programming...
# 3
SomeObject o = null;o.someStaticMethod();Yay.
CeciNEstPasUnProgrammeura at 2007-7-9 20:33:04 > top of Java-index,Java Essentials,Java Programming...
# 4
SomeObject o = null;o.someStaticMethod();It is possible but I would not forcibly call it best practice...
BIJ001a at 2007-7-9 20:33:04 > top of Java-index,Java Essentials,Java Programming...
# 5

1. By using the class name, you don't have to create objects of that classes for being able to call static methods.

2. Everyone (including yourself) who reads your code will see that this is a call of a static method.

3. Static methods can't be overriden. For this reason, you know at compile time exactly which static method (i. e. which static method of which class) will be called. So make the information directly visible to the reader.

ProggerFromKupfera at 2007-7-9 20:33:04 > top of Java-index,Java Essentials,Java Programming...
# 6
> It is possible but I would not forcibly call it best> practice...I know it's possible, but it's most ugly.
CeciNEstPasUnProgrammeura at 2007-7-9 20:33:04 > top of Java-index,Java Essentials,Java Programming...
# 7
> 1. By using the class name, you don't have to create> objects of that classes for being able to call static> methods.You don't have to either way. See my example.
CeciNEstPasUnProgrammeura at 2007-7-9 20:33:04 > top of Java-index,Java Essentials,Java Programming...