java基础知识7this关键字

来源:互联网 发布:三星专用下载软件 编辑:程序博客网 时间:2024/06/09 15:38


this关键字

    普通方法中,this总是指向调用该方法的对象。

    构造方法中,this总是指向正要初始化的对象。

this最常的用法:

    1.   让类中的一个方法,访问该类的另一个方法或属性。

    2.    使用this关键字调用重载构造方法。避免相同的初始化代码,只能在构造方法中用,并且必须位于构造方法的第一句。

this使用时的注意事项:

    ·this不能用于static方法!(this指向当前对象,static方法跟对象没有一毛钱的关系)

//

package this用法;

//主类

publicclassTest {

 

 publicstaticvoid main(String[]args) {

    StudentA =new Student();

    A.eatFood();

    StudentB =new Student();

    Stringn ="wanger";

     B.Student(n,12);

 }

 

}

 

//学生类

class Student

{

 //属性

 intage;

 Stringname;

 

 //方法

 publicvoid eatFood()//普通方法里面没有参数,但调用时会默认传个参数this

 {

    this.name="李四";

    /*普通方法中,this指的是当前正在调用该方法的对象。也就是A,所以this.name就是A.name;

     * 其中this.可以不写,会默认的

     */

    System.out.println(name);

 }

 

 public Student()

 {

    System.out.println("构造方法1");

 }

 public Student(Stringname)

 {

    System.out.println("构造方法2");

 }

 public Student(Stringname,intage)

 {

    this(name);//使用this关键字调用重载构造方法。避免相同的初始化代码,只能在构造方法中用,并且必须位于构造方法的第一句。

    this.age=age;//构造方法中,this总是指向正要初始化的对象

    this.name=name;

 }

 

}

0 0