Java 为什么不能使用;这";主要方法是什么?

Java 为什么不能使用;这";主要方法是什么?,java,Java,我是java新手。为什么我不能在主方法中使用“this”?此引用当前对象。但是,main方法是静态的,这意味着它附加到类,而不是对象实例,因此main()中没有当前对象 为了使用this,您需要创建类的实例(实际上,在本例中,您没有使用this,因为您有一个单独的对象引用。但是您可以在m()方法中使用this,例如,因为m()是存在于对象上下文中的实例方法): 顺便说一句:您应该熟悉Java命名约定——类名通常以大写字母开头。您必须创建一个示例实例 public static void main

我是java新手。为什么我不能在主方法中使用“this”?

引用当前对象。但是,
main
方法是静态的,这意味着它附加到类,而不是对象实例,因此
main()
中没有当前对象

为了使用
this
,您需要创建类的实例(实际上,在本例中,您没有使用
this
,因为您有一个单独的对象引用。但是您可以在
m()
方法中使用
this
,例如,因为
m()
是存在于对象上下文中的实例方法):


顺便说一句:您应该熟悉Java命名约定——类名通常以大写字母开头。

您必须创建一个示例实例

public static void main(String[] args){
    example e = new example();
    int c=e.a;
}

因为main是静态的。要访问
a
,您还应该将其声明为
static
。静态变量不存在该类的任何实例。非静态变量只有在实例存在时才存在,并且每个实例除了Andreas的注释外,还有自己的名为
a

的属性

example e = new example()
e.m()
如果您想使用“a”。然后您必须实例化新的示例[最好将示例类名设为大写Eaxmple]

差不多

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.
    }
}

HTH

main方法是静态的,这意味着可以在不实例化
示例
类的情况下调用它(静态方法也可以称为类方法)。这意味着在
main
的上下文中,变量
a
可能不存在(因为
example
不是实例化对象)。同样,如果不先实例化
example
,就不能从
main
调用
m

public static void main(String[] args) {
  Example e = new Example();
  int c = e.a;
}
补充答覆:


main是静态方法,但变量
a
是非静态的。为什么要拒绝投票而不提及原因?这是一个好问题。
public static void main(String[] args) {
  Example e = new Example();
  int c = e.a;
}
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".
    }
}