So I looked online through a number of resources to understand Java interfaces. I believe I have a good general understanding of them but when programming them I am a bit confused…
I created an interface called A and have the following inside…
public interface A {
public int sum(int first, int second);
}
I then created a class called B.
public class B implements A {
public static void main(String [] args){
int result = sum(3, 5);
}
public int sum(int first, int second) {
int total = first + second;
return total;
}
}
Now what I am trying to figure out is how can I properly call / use the method “sum”. In Eclipse I’m getting an error for the line “int result = sum(3, 5);” and it is telling me to make the method static. If I make it static, then the method needs to match it in the interface. However, I am not able to use static methods in an interface?
Any help is appreciated and thank you for your time to read about my problems.
The issue you have is not of interface but of
staticmethod.mainis astaticmethod. That means it is not linked to an object/instance, but to the class itself.Since you want to use
sum, which is an instance method, you need first to create an object to call its method.Usually, instance methods are more linked to the object status, while static methods are more like “procedures” in non OO languages. In the case of
sum, your method would make more sense as static. But, if you useBto wrap a value (status), and use sum to add to your internal status, this would end (in a more OO friendly way).Note that both approachs are valid and both compile in Java, it is just a matter of selecting the modifiers that make more sense in each occasion.