I came across this code in hackerrank.com which made me ask this question:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
static int solveMeFirst(int a, int b) {
return a+b;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a;
a = in.nextInt();
int b;
b = in.nextInt();
int sum;
sum = solveMeFirst(a, b);
System.out.println(sum);
}
}
why is this possible? Here, shouldn't it be Solution.solveMeFirst(a,b);
Here, shouldn't it be Solution.solveMeFirst(a,b);
You could call it that, but you certainly don't have to.
The detailed rules for finding the meaning of a name are given in JLS 6.5, but basically the compiler will search through the "current" class (the one that you're calling it from) and all ancestor classes (in this case just Object
). It will also use any static imports (which you don't have in this case).
It's just the same with instance methods:
public class Foo {
public void firstMethod() {
secondMethod();
}
private void secondMethod() {
}
}
An instance method can call a static method without any qualification, but a static method can't call an instance method without specifying the instance on which to call the method, e.g.
public class Foo {
public static void staticMethod(Foo instance) {
instance.instanceMethod();
}
private void instanceMethod() {
}
}
See more on this question at Stackoverflow