public class test {
public static void main(String[] args) {
System.out.println("计算加法:");
int a = 10, b = 7;
Plus plus = new Plus();
System.out.println(a + " + " + b + " = " + plus.Add(a, b));
}
class Plus {
public int Add(int x, int y) {
return x + y;
}
}
}
2 “出错”原因解析
- 静态方法或变量:被
static
关键字修饰,可通过类直接调用。 - 非静态方法或变量:依赖于对象,是对象的属性,只有先实例化对象,才能使用。
-
错误的原因:无法从静态上下文中(
main
)引用非静态 变量this (Plus
)。 -
修改方法:将类
Plus
放在类test
外面。
3 修改后的正确代码
public class test {
public static void main(String[] args) {
System.out.println("计算加法:");
int a = 10, b = 7;
Plus plus = new Plus();
System.out.println(a + " + " + b + " = " + plus.Add(a, b));
}
}
class Plus {
public int Add(int x, int y) {
return x + y;
}
}
4 编译、运行及结果 4.1 编译命令 (支持中文)
javac -encoding utf-8 test.java
4.2 运行
java test
4.3 输出结果
计算加法:
10 + 7 = 17
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)