现在的位置: 首页 > 综合 > 正文

java 中 this 类名 对象名 的作用

2013年09月18日 ⁄ 综合 ⁄ 共 857字 ⁄ 字号 评论关闭

 

this 表示“当前对象”,不能用在静态的方法中。

对象象你知道的就有很多拉,变量拉,线程等等。

1.This用来表示全局变量
public class TestClass
{
  int x,y;
  void testShow(int x,int y){
  this.x=x; //this.x 就是我们上 int x,y;中的X 。x是我们传来的x
  this.y=y;
  }
} 

2.

public class TestClass 
{ 
  int x;
  int y;

  static void showtest(TestClass tc){
   System.out.println(tc.x+"  "+tc.y);
  }


  void seeit(){
    showtest(this);
  }

  public static void main(String[] args){
    TestClass p=new TestClass();
    p.x=9;
    p.y=10;
    p.seeit();
   }
} 
这段代码中showtest(this),这里的this就是把当前实例化 的 p传给了showtest方法,从而就运行了。

 

类名用来访问静态成员;

public class Test {

    private float f = 1.0f;

    int m = 12;

    static int n = 1;

    //public  static void main(String[] args) {

    public void main(String[] argc){

        Test t = new Test();

        Test.n = 10;

    }

}

对象名可以访问静态和非静态成员

public class Test {

    private float f = 1.0f;

    int m = 12;

    static int n = 1;

    //public  static void main(String[] args) {

    public void main(String[] argc){

        Test t = new Test();

        Test.n = 10;

        t.m = 10;

        t.n = 10;

    }

}

抱歉!评论已关闭.