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?

3 Answers 3

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)

Sign up to request clarification or add additional context in comments.

2 Comments

True but that's in bad form, yes?
Hopefully, but for completeness, it must be brought up.
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.

4 Comments

Java uses that to tell them apart.
Eclipse uses Java to tell them apart.
And Java uses the class name to tell them apart. Eclipse has nothing to do with it. The program compiles and executes identically whether or not Eclipse is even there, modulo Eclipse peculiarities.
Right, but the question asked how does Eclipse know the difference so I thought I'd keep it simple.
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.

2 Comments

Although it's generally considered bad practice to use an instance (i.e. c.parseInt()) to call a static method.
What the answer said is if its static, use the class name. If it is not static, use an instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.