37

xiaoxiao2021-02-27  206

this关键字:

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

this最常的用法:

让类中的一个方法,访问该类的另一个方法或属性。使用this关键字调用重载构造方法。避免相同的初始化代码,只能在构造方法中用,并且必须位于构造方法的第一句。

this使用时的注意事项:

this不能用于static方法!(this指向当前对象,static方法跟对象没有一毛钱的关系)this和super是隐式参数,默认传递this实质上是指向当前对象的一个地址

package cn.bjsxt.oop.testThis; public class Student { String name; int id; public Student(String name,int id){ this(name); //this(); //通过this调用其他构造方法,必须位于第一句!Constructor call must be the first statement in a constructor this.name = name;//this用于构造方法 this.id = id; } public Student(String name){ this.name = name; } public Student(){ System.out.println("构造一个对象"); } public void setName(String name){ this.name = name;//this用于set或get方法 } public void study(){ this.name= "张三";//引用当前对象的属性或方法 System.out.println(name+"在學習"); } public void sayHello(String sname){ System.out.println(name+"向"+sname+"說:你好!"); } }
转载请注明原文地址: https://www.6miu.com/read-8496.html

最新回复(0)