对于我正在进行的练习,我有三个方法,所有isEven都测试一个值并返回true或false。一个isEven是一个实例方法,另外两个是静态方法,每个方法都有一个参数。如果我创建一个新的testClass,并在main方法中运行方法,则实例isEven方法工作正常,但是当我尝试使用静态isEven方法时,我得到一个符号未找到错误。但是,如果我在实际的app类中创建main方法并在那里运行它,重载的方法将起作用。为什么会这样?静态方法不能在另一个类中运行吗?使用的方法如下。
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);
}
}
答案 0 :(得分:1)
让我们来看看你的代码:
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
方法与免费方法不同。您仍然需要使用类或通过该类的实例来调用它们。
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);
}
答案 1 :(得分:0)
这里有几个问题。他们在评论中有解释,但我会在这里列出:
你的main()方法在同一个java文件中,但不是同一个类。它们是两个非常不同的东西。
public class MyInteger {
// Not included in post
private int value;
// Not included in post
public MyInteger(int i) {
value = i;
}
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.getValue()); // mispelled here, Not declared anyways
val1.isEven();
// these are not declared
//val1.isOdd();
//val1.isPrime();
// Not inside of the 'MyInteger class, therefor not able to be called without static reference of MyInteger.isEvent
//isEven(val1);
MyInteger(val1);
}
}