class B {
int x,y;
int z;
z=x*y;
void show() {
System.out.println(z);
}
}
class A {
public static void main(String as[]) {
B b=new B();
b.show();
}
}
- 积分
0 - 话题
0 - 评论
3221 - 注册排名
1540
class B {
int x,y;
int z;
z=x*y;
void show() {
System.out.println(z);
}
}
class A {
public static void main(String as[]) {
B b=new B();
b.show();
}
}
z=x*y;
you cant do it here. put it inside constructorYou can't have statements in the class body (
z=x*y;
). You have (at least) two options:int z = x * y;
use initializer block
These are virtually the same. I'd prefer the first option (cleaner) See here
我认为您的问题出在以下几行:
This first line is perfectly fine - it declares a class instance variable called
z
of typeint
. This second line, however, is the source of your problem. In Java, it's illegal to have code in a class outside of a class method or static initializer. In this case, the statementz = x * y;
is legal Java code, but it has to be inside of a method.要解决此问题,可以将此代码移到构造函数或其他方法中。
提到不在方法体内。你不能那样做。将其移动到构造函数或其他方法。
内部类主体和外部方法主体只能提及字段,方法和内部类声明。