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,610
  • 2
  • 33
  • 42
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
  • 4,494
  • 4
  • 35
  • 47
Jonathan Spooner
  • 7,610
  • 2
  • 33
  • 42
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,047
  • 22
  • 82
  • 113
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
  • 4,494
  • 4
  • 35
  • 47
ewok
  • 18,668
  • 45
  • 132
  • 245
  • 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