喜悦国际村 » JAVA/C/C++ » java中this使用的问题

页: [1]
kayej2005-5-23 01:58 PM
java中this使用的问题

我在使用this出现了问题:
我的代码如下:
[CODE]
/*
* RangeClass.java
*
* Created on 2005年4月3日, 下午8:33
*/

package lesson5;

/**
*
* @author  Administrator
*/
public class RangeClass {
    int test = 10;
    /** Creates a new instance of RangeClass */
    public RangeClass() {
    }
    int[] makeRange (int lower,int upper){
        int[] arr = new int[(upper-lower) + 1];
        for (int i=0; i<arr.length; i++)
            arr[i] = lower++;
        return arr;
    }
    void printTest(){
        int test = 20;
        System.out.println("Test:" + this.test);
    }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] theArray;
        RangeClass theRange = new RangeClass();

        theArray = theRange.makeRange(5, 10);
        System.out.print("The array: [");
        for (int i=0; i<theArray.length; i++)
              System.out.print(theArray[i] + " ");
        System.out.println("]");     
        theRange.printTest();
        System.out.println("Test:" + this.test); //如果我不运行这句就对了
    }   
}
[/CODE]

报错:
lesson5/RangeClass.java [42:1] non-static variable this cannot be referenced from a static context
        System.out.println("Test:" + this.test);
                                     ^
1 error
Errors compiling test.

问题:
1.如果我要在main函数中调用this.test怎么操作?
2.是不是在static的函数中都不能用this.test调用吗?如果不能,怎么调用
3.我吧:
public class RangeClass {
    int test = 10;
改成了:
public class RangeClass {
   static int test = 10;
也不行

如果要调用static的变量,怎么调用?

雨伞2005-5-23 03:52 PM
static修饰的main方法在运行的时候实际上还没有this的存在。

static int test = 10;
...
System.out.println("Test:" + test);

tokeng2005-5-30 08:40 AM
[发现]一个this的用法

类的成员变量名与当前方法中的形参名或者
与当前方法中的局部变量名相同时,就要求
用this关键字引用类的成员变量。


查看完整版本: java中this使用的问题


Powered by Discuz! Archiver 6.1.0  © 2001-2006 Comsenz Inc.
Processed in 0.005768 second(s), 2 queries