public class example {
int a = 0;
public void m() {
int b = this.a;
}
public static void main(String[] args) {
int c = this.a;
}
}
我是java新手。为什么我不能在主要方法中使用“this”?
public class example {
int a = 0;
public void m() {
int b = this.a;
}
public static void main(String[] args) {
int c = this.a;
}
}
我是java新手。为什么我不能在主要方法中使用“this”?
this指当前对象。但是,该main方法是静态的,这意味着它附加到类,而不是对象实例,因此内部没有当前对象main()。
为了使用this,你需要创建你的类的一个实例(实际上,在这个例子中,你没有使用,this因为你有一个单独的对象引用。但是你可以this在你的m()方法中使用,例如,因为m()它是一个实例方法存在于对象的上下文中):
public static void main(String[] args){
example e = new example();
int c=e.a;
}
顺便说一句:您应该熟悉 Java 命名约定 - 类名通常以大写字母开头。
您必须创建示例的实例
example e = new example()
e.m()
因为主要是static. 要访问a,您也应该声明它static。静态变量在没有任何类实例的情况下存在。非静态变量仅在实例存在时才存在,并且每个实例都有自己的名为 的属性a。
public class Example {
int a = 0;
// This is a non-static method, so it is attached with an instance
// of class Example and allows use of "this".
public void m() {
int b = this.a;
}
// This is a static method, so it is attached with the class - Example
// (not instance) and so it does not allow use of "this".
public static void main(String[] args) {
int c = this.a; // Cannot use "this" in a static context.
}
}
除了安德烈亚斯的评论
如果你想使用'a'。然后您将必须实例化新示例[最好将示例类名设为大写 Eaxmple]。
就像是
public static void main(String[] args) {
Example e = new Example();
int c = e.a;
}
高温高压
该main方法是静态的,这意味着它可以在不实例化example类的情况下调用(静态方法也可以称为类方法)。这意味着在 的上下文中main,变量a可能不存在(因为example不是实例化对象)。同样,您不能m在main没有先实例化的情况下调用example:
public class example {
int a=0;
public void m(){
// Do stuff
}
public static void main(String[] args){
example x = new example();
x.m(); // This works
m(); // This doesn't work
}
}
安德烈亚斯·费斯特的补充回答:
/****GRAMMER:
*
* Why cannot use "this" in the main method?
*
* -----------------------------------------------------------------------------------
*
* "this" refers to the current object. However, the main method is static,
* which means that it is attached to the class, not to an object instance.
*
* Which means that the static method can run without instantiate an object,
* Hence, there is no current "this" object inside of main().
*
*
*/
public class Test{
int a ;
public static void main(String[] args) {
int c = this.a; // Cannot use "this" in a static context,
// because there isn't a "this".
}
}