2

I know the definition of static which is a keyword to refer a variable or method to the class itself. Could this mean if I wrote a method called parseInt() in a class called calculator and another method called parseInt() in a different class called mathProgram, the compiler Eclipse will know which class the method parseInt() is referring to?

Jonathan Spooner
  • 7,682
  • 2
  • 34
  • 41
Nicholas Kong
  • 129
  • 2
  • 4
  • 7

3 Answers3

4

You need to call static methods by referencing the class it is a part of:

MathProgram.parseInt();

Is not the same as

Calculator.parseInt();

So written this way it is clear to the JVM which method you were referring to.

Edit: You can also call static methods using an instance variable but this is in bad form and should be avoided. See this SO answer for more info.

Edit2: Here's a link to the Java Coding Conventions section regarding the use of calling static methods from instance variables. (Thanks to Ray Toal for the link left in the answer to a question posted here)

cb4
  • 6,689
  • 7
  • 45
  • 57
Jonathan Spooner
  • 7,682
  • 2
  • 34
  • 41
2

Yes, because static methods and variables must be in a class and to call them outside of that class you need to qualify them.

For example Calculator.parseInt() and OtherClass.parseInt().

Eclipse uses that to tell them apart.

cdmckay
  • 31,832
  • 25
  • 83
  • 114
1

If the method is static, you need to call it using the classname:

Calculator.parseInt();

Otherwise, with an instance:

Calculator c = new Calculator();
c.parseInt();

Either way, its explicit which you want.

cb4
  • 6,689
  • 7
  • 45
  • 57
ewok
  • 20,148
  • 51
  • 149
  • 254
  • Although it's generally considered bad practice to use an instance (i.e. `c.parseInt()`) to call a static method. – cdmckay Oct 25 '11 at 04:01
  • What the answer said is if its static, use the class name. If it is not static, use an instance. – ewok Oct 25 '11 at 12:19