日期:2014-05-20  浏览次数:20771 次

关于this
public   class   e
{
static   int   n=1;
public   static   void   main(String[]   args)
{
e   e1=new   e();
System.out.println(this.n);
}
}
帮忙看看代码,这里的this.n为什么不可以,希望从基本原来给解释一下,谢谢

------解决方案--------------------
this是一个动态的变量,指向当前类的实例,而静态方法是不需要实例化就可以使用的方法,所以不能在静态方法中使用

------解决方案--------------------
静态方法里没有this
------解决方案--------------------
静态变量是通过类名引用,而this的用途是针对具体的对象。

比如
public class T
{
public static int n=1;
public int m;
public T(int m)
{
this.m=m;
}
public static void main(String[] args)
{
T t1=new T(1);
T t2=new T(2);
System.out.println(t1.m);
System.out.println(t2.m);
T.n=33;
System.out.println(t1.n);
System.out.println(t2.n);
}
}
上面的this就是指特定的对象,t1和t2的m值就不一样,但是n值是一样的
------解决方案--------------------
这个this显然不能用。。。。编译没有报错吗?建议楼主在写代码的时候还是用诸如eclipse或者jbuilder等能检测这种基本错误的编写工具比较好。

this是基于本类而言,准确说是指向的类的一个具体的实例,所以,this只能用于非静态方法中。main属于静态方法,肯定是不能使用的。。。。

这种问题说明楼主的基本功还是不够扎实,多看看基础内容吧
------解决方案--------------------
静态方法中不可以使用this
------解决方案--------------------
静态方法是没有this的概念的

------解决方案--------------------
我也刚想问这个问题
觉得CSDN真是个好地方
------解决方案--------------------
main是static的;
this不是static的;

static的main中只能调用static的方法以及变量!
------解决方案--------------------
this 是当前实例的一个代理
static对象是属于类的,不属于对象