Artie Artie - 3 months ago 14
Java Question

Overloaded static methods not running in other class?

For an exercise I am doing I have three methods, all isEven that tests a value and returns true or false. One isEven is an instance method, and the other two are static methods each with one parameter. If I make a new testClass, and run the methods in the main method the instance isEven method works fine, however when I try and use the static isEven methods I get a symbol not found error. However, if I create the main method in the actual app class and run it there the overloaded methods will work. Why is this happening? Shouldn't the static methods be able to run in another class? The methods used are below.

public class MyInteger {
private int value;
public boolean isEven() {
if(this.value % 2 == 0) {
System.out.println(value + " is an even number.");
return true;
}
else {
System.out.println(value + " is not an even number.");
return false;
}
}

public static boolean isEven(int value) {
if(value % 2 == 0) {
System.out.println(value + " is an even number.");
return true;
}
else {
System.out.println(value + " is not an even number.");
return false;
}
}

public static boolean isEven(MyInteger value) {
if(value.value % 2 == 0) {
System.out.println(value.value + " is an even number.");
return true;
}
else {
System.out.println(value.value + " is not an even number.");
return false;
}
}
}
class testMyInteger {
public static void main(String[] args) {
MyInteger val1 = new MyInteger(2);
int val = 2;
System.out.println("The value of this object is " + val1.getValu());
val1.isEven();
val1.isOdd();
val1.isPrime();
isEven(val1);
}
}

Answer

Let's look at your code:

public static void main(String[] args) {
    MyInteger val1 = new MyInteger(2);
    int val = 2;
    System.out.println("The value of this object is " + val1.getValu());
    val1.isEven();
    val1.isOdd();
    val1.isPrime();
    isEven(val1); // <-- here is the problem.
}

static methods are not like free methods. You still need to invoke them with a class, or through an instance of that class.

E.g.:

 public static void main(String[] args) {
    MyInteger val1 = new MyInteger(2);
    int val = 2;

    MyInteger.isEven(val1);
    val1.isEven(val1);

    MyInteger.isEven(val);
    val1.isEven(val);
}