一、this
this是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个引用。
this的用法在java中大体可以分为3种:
1、普通的直接引用
this相当于是指向当前对象本身。
2、形参与成员名字重名,用this来区分:
public Person(String name, int age) {
> this.name = name;
> this.age = age; }
3.调用本类的其他构造方法
依赖形参和实参的关系
class Person{
private String name;
private int age;
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(String name, int age) {
this(name);
this.age = age;
}
}
二、super
super可以理解为是指向自己父类对象的一个引用,而这个父类指的是离自己最近的一个父类
super也有三种用法:
1、普通的直接引用与this类似,super相当于是指向当前对象的父类对象部分的引用,这样就可以用super.xxx来引用父类的成员。
2、子类中的属性行为或方法与父类中的属性行为或方法同名时,用super进行区分
当子类重写父类型为 super.调用父类实现 this.调用子类实现
class Person{
protected String name;
public Person(String name) {
this.name = name;
}
}
class Student extends Person{
private String name;
public Student(String name, String name1) {
super(name);
this.name = name1;
}
public void getInfo(){
System.out.println(this.name); //Child
System.out.println(super.name); //Father
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student("Father","Child");
s1.getInfo();
}
}
三、引用父类构造函数
super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。
this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。
四、super和this的异同:
super:它引用父类中的成员
super.成员函数据名(实参)this:它代表当前对象名
super()和this()类似,区别是,super()在子类中调用父类的构造方法,this()在本类内调用本类的其它构造方法。super()和this()均需放在构造方法内第一行。 尽管可以用this调用一个构造器,但却不能调用两个。
this和super不能同时出现在一个构造函数里面,因为this必然会调用其它的构造函数,其它的构造函数必然也会有super语句的存在,所以在同一个构造函数里面有相同的语句,就失去了语句的意义,编译器也不会通过。
this()和super()都指的是调用构造方法,所以,均不可以在static环境中使用。包括:static变量,static方法,static语句块。