美好的一天!
我是Java的初学者.我无法编译以下代码:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
Run Code Online (Sandbox Code Playgroud)
出现以下错误:
__CODE__
这是什么意思?我该如何解决这个问题..?
您的回复将受到高度赞赏.谢谢
根据您的建议,我创建了一个新的test()实例,如下所示:
public class Test {
int num;
public static void main (String [] args ){
Test a = new Test();
a.num = a.calcArea(7, 12);
System.out.println(a.num);
}
int calcArea(int height, int width) {
return height * width;
}
}
Run Code Online (Sandbox Code Playgroud)
它是否正确?如果我这样做有什么区别......
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
Run Code Online (Sandbox Code Playgroud)
你的main是静态的,所以你可以在没有类test(new test())的实例的情况下调用它.但它调用calcArea哪个不是静态的:它需要一个类的实例
你可以像这样重写它我猜:
public class Test {
public static void main (String [] args ){
int a = calcArea(7, 12);
System.out.println(a);
}
static int calcArea(int height, int width) {
return height * width;
}
}
Run Code Online (Sandbox Code Playgroud)
正如评论所暗示的那样,以及其他答案也表明,你可能不想走这条路线进行翻转:你只会获得静态功能.弄清楚代码中实际应该是什么静态,并且可能使自己成为一个对象并从那里调用函数:D
Nanne 的建议绝对可以解决您的问题。但是,我认为,如果您现在就养成了这样的习惯,即在学习 java 的早期阶段,尝试尽可能少地使用静态方法,除非适用(例如实用程序方法) 。以下是修改后的代码,用于创建 Test 实例并调用 Test 对象上的 calcArea 方法:
public class Test {
public static void main (String [] args ){
Test test = new Test();
int a = test.calcArea(7, 12);
System.out.println(a);
}
int calcArea(int height, int width) {
return height * width;
}
}
Run Code Online (Sandbox Code Playgroud)
当您进一步使用 java 进行编码时,假设您刚刚编写的代码开始处理诸如某种多边形对象之类的对象,像 calcArea 这样的方法属于实例上下文而不是静态上下文,因此它可以操作关于对象的内部状态。这将使您的代码更加面向对象并且更少程序化。