this
-
this
代表对象本身,相当于是对象自身的一个指针。 -
this
的三种用法:- 1 直接引用对象本身。
- 2 形参与成员名字重名,用this来区分。
- 3 引用本类的构造函数。
-
测试:
public class Test {
public static void main(String[] args) {
Person p=new Person();
//this直接引用
System.out.println(p);//打印p对象的地址
p.soutThis();//调用p对象中打印this的方法 可以发现,二者完全一致
}
}
class Person{
int sex;
int age;
public Person(){
}
public Person(int sex){
//此处 形式参数和成员变量重名,this.sex代表该对象的成员变量
this.sex=sex;
}
public Person(int sex,int age){
//这里this代表引用本类中的构造方法
this(sex);
this.age=age;
}
public void soutThis(){
//此处打印对象自身的地址
System.out.println(this);
}
}
super
-
super
代表父类对象(离自己最近的一个父类),相当于是父类的一个指针。 -
super
的三种用法:- 1 直接引用父类。
- 2 子类中的成员变量或方法与父类中的成员变量或方法同名时,用super进行区分。
- 3 引用父类构造函数
-
测试:
public class Test {
public static void main(String[] args) {
Orange orange=new Orange(5,"orange","Lorange");
}
}
class Orange extends Fruit{
String name;
public Orange(int size,String color,String name){
//调用父类的构造方法
super(size,color);
this.name=name;
}
public void info1(){
//此处super用于区分子类与父类名字相同的成员变量
System.out.println(this.name);
System.out.println(super.name);
}
public void info2(){
//此处super直接引用父类的成员变量
System.out.println(super.size);
}
}
class Fruit{
int size;
String color;
String name;
public Fruit(){
}
public Fruit(int size,String color){
this.size=size;
this.color=color;
}
public Fruit(int size,String color,String name){
this.size=size;
this.color=color;
this.name=name;
}
}
注意事项:
-
(1)使用
super
调用父类中的某一个构造函数时,该语句应该为构造函数中的第一条语句。 -
使用
this
调用本类中另一种形式的构造函数,该语句应该为构造函数中的第一条语句。 -
(2)
this
和super
对成员方法和成员变量的使用是一样的。 -
(3)
this
和super
都是指的对象实例,所以不能再任何static
语句中使用。 -
(3)不能使用
this
调用两个构造方法。 -
(4)his和super不能同时出现在一个构造函数里面。
- 因为每一个子类的构造函数中的第一行都有一条默认的隐式语句
super();
,this
调用的其它构造方法必然也会有这条语句,这样就会冲突,失去了语句本身的意义。
- 因为每一个子类的构造函数中的第一行都有一条默认的隐式语句