目录
1. this:理解为一个变量,表示当前方法调用者的地址值;
1. this:理解为一个变量,表示当前方法调用者的地址值;
public class Student {
String name;
int age;
// Student this是虚拟机默认生成的
public void show (Student this){
System.out.println(this.name+" ,"+this.age)
}
}
// 测试类
public class Test{
public static void main(String[]args){
Student s1=new Student();
s.name="张三";
s.age=23;
s.show();
/*对象s调用show方法,
对象s的地址值被作为实参传入this*/
2. super:代表父类的存储空间。
3.this和super的使用格式:
访问成员变量和方法时this或super .
访问构造方法时this或super()
红字解释
当使用this访问构造方法时:我们一般是用来为成员变量初始化值。
详见下面代码:
public class Student {
String name;
int age;
String school;
/*
需求:默认为清华大学
*/
public Student() {
//表示调用本类中的其他构造方法
//细节:这样虚拟机就不会再添加super();
this(null, 0, "清华大学");
// school="北京大学"; //或者这样写,也可在创建对象时初始化学校
}
public Student(String name, int age, String school) {
this.name = name;
this.age = age;
this.school = school;
}
}
public class Test {
public static void main(String[] args) {
Student u=new Student();
System.out.println(u.school);//清华大学
}
}