1、this
1.1、this是一个关键字,是一个引用,保存内存地址指向自身。
1.2、this可以使用在实例方法中,也可以使用在构造方法中。
1.3、this出现在实例方法中其实代表的是当前对象。
1.4、this不能使用在静态方法中。
1.5、this. 大部分情况下可以省略,但是用来区分局部变量和实例变量的时候不能省略。
1.6、this() 这种语法只能出现在构造方法第一行,表示当前构造方法调用本类其他的
构造方法,目的是代码复用。
1.7 this() 不能和super() 共存;
public class Test06 {
public static void main(String[] args) {
//创建一个对象
Animal a = new Animal();
//引用
a.setName("旺财");
System.out.println(a.getName());
a.showAnimal();
/*
* Animal a2 = new Animal("舔狗"); System.out.println(a2.getName());
* a2.showAnimal();
*/
Animal a3 = new Animal();
System.out.println(a3.getName());
a3.showAnimal();
}
}
class Animal {
private String name ; //实例变量
//无参构造
public Animal() {
this("李四"); //调用有参;可以使用在构造方法中。
}
public Animal(String name) {
this.name = name;
}
//只能通过get方法读取,
public String getName() {
return name;
}
//外部程序只能通过set方法修改,
public void setName(String name) {
this.name = name;//this可以使用在实例方法中
}
public void showAnimal() {
System.out.println(this);//this是一个关键字,是一个引用,保存内存地址指向自身。
}
}
qq:1756058054