java中的关键字(一)

来源:互联网 发布:开个淘宝店卖什么好 编辑:程序博客网 时间:2024/05/17 16:46

    java视频中讲了this关键字的用法,这里详细讲解一下。

1.当成员变量和局部变量重名时,在方法中使用this时,表示的是该方法所在类中的成员变量。(this是当前对象自己)

如:

public class Hello {    String s = "Hello";     public Hello(String s) {       System.out.println("s = " + s);       System.out.println("1 -> this.s = " + this.s);       this.s = s;//把参数值赋给成员变量,成员变量的值改变       System.out.println("2 -> this.s = " + this.s);    }     public static void main(String[] args) {       Hello x = new Hello("HelloWorld!");       System.out.println("s=" + x.s);//验证成员变量值的改变    }}
结果为:

s = HelloWorld!1 -> this.s = Hello2 -> this.s = HelloWorld!s=HelloWorld!

    在这个例子中,构造函数Hello中,参数s与类Hello的成员变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类Hello的成员变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对构造函数中传递过来的参数s进行打印结果; 第二行是对成员变量s的打印;第三行是先对成员变量s赋传过来的参数s值后再打印,所以结果是HelloWorld!而第四行是主函数中直接打印类中的成员变量的值,也可以验证成员变量值的改变。

2.在构造函数中,通过this可以调用同一类中别的构造函数。

 

public class ThisTest {    private int age;    private String str;     ThisTest(String str) {       this.str=str;       System.out.println(str);    }    ThisTest(String str,int age) {       this(str);       this.age=age;       System.out.println(age);    }     public static void main(String[] args) {       ThisTest thistest = new ThisTest("this测试成功",25);          }}

结果为:

this测试成功25

    在这个例子中main()函数调用第二个构造函数ThisTest(string str,int age),执行这个函数的第一句this(str)时,调用构造函数ThisTest(string str)


3.把自己当作参数传递时,也可以用this.(this作当前参数进行传递)

 class A {    public A() {       new B(this).print();// 调用B的方法    }    public void print() {       System.out.println("HelloAA from A!");    }}class B {    A a;    public B(A a) {       this.a = a;    }    public void print() {       a.print();//调用A的方法       System.out.println("HelloAB from B!");    }}public class HelloA {    public static void main(String[] args) {       A aaa = new A();       aaa.print();       B bbb = new B(aaa);       bbb.print();    }}

结果为:

HelloAA from A!HelloAB from B!HelloAA from A!HelloAA from A!HelloAB from B!

   在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。

4.this同时传递多个参数。

  

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();    }}
结果为:

9 10

  代码中的showtest(this),这里的this就是把当前实例化的p传给了showtest()方法,从而就运行了。

this关键字通俗的说指当前对象,这几种用法慢慢参透就会明白,希望大家能做补充。


0 0
原创粉丝点击