java基础 this和super的介绍
this和super
- this关键字的用法
- super关键字的用法
- this与super的区别和注意事项
this关键字的用法
this是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个指针
class Person{
private String name;
private int age;
public String getName() {
return name;
}
//①普通的直接引用,this相当于是指向当前对象本身
public void setName(name) {
this.name = name;
}
public Person() {}
//②形参与成员名字重名,用this来区分
public Person(String name) {
this.name = name;
}
//③引用本类的构造函数 (应该为构造函数中的第一条语句)
public Person(String name, int age) {
this(name);
this.age = age;
}
}
super关键字的用法
super可以理解为是指向自己超(父)类对象的一个指针,而这个超类指的是离自己最近的一个父类
super也有三种用法:
class Person {
protected String name;
public Person(String name) {
this.name = name;
}
public String getName(){
return this.name;
}
}
public class Sun extends Person{
private String name;
// ①普通的直接引用,super.xxx来引用父类的成员
String superName=super.name;
//super.xxx()来引用父类的方法
String superGetName=super.getName();
public Sun(String name) {
//②引用父类构造函数(应该为构造函数中的第一条语句)
super(name);
}
//③子类中的成员变量或方法与父类中的成员变量或方法同名时,用super进行区分
public Sun(String name, String name1) {
super(name);
this.name = name1;
}
public void getInfo(){
System.out.println(this.name); //Child
System.out.println(super.name); //Father
}
}
this与super的区别和注意事项
this与super的区别:
1.指代上的区别
(1)super:是对当前对象中父对象的引用
(2)This:指当前对象的参考。
2.引用对象上的区别
(1)super.xxx:直接父类中引用当前对象的属性或方法
(2)This.xxx:表示当前对象的本类属性或方法
3.调用函数上的区别
(1)super():在基类中调用构造函数(是构造函数中的第一条语句)
(2)This():在此类中调用另一个结构化的构造函数(是构造函数中的第一条语句)
从本质上讲,this是一个指向本对象的指针, 然而super是一个Java关键字
this与super注意事项:
①super()和this()都必须在构造函数的第一行进行调用,否则就是错误的
②this.xxx和super.xxx可以同时出现,this()和super()不能同时出现在一个构造函数里面
- this.xxx和super.xxx意思是this调用本类属性或方法、super调用父类属性或方法时,可以同时出现
- this()和super()是this调用本类构造器、super调用父类构造器时,构造函数作用就是构造对象的,这样同时出现,不知道返回哪个对象了,没有意义,编译也不会通过
③this()和super()都指的是对象,所以均不可以在static环境中使用。包括:static变量,static方法,static语句块,因为static表示“类去实例化”,作用对象是类,this()和super()作用的是对象,是要被调用的,他两个和对象有关,static和类有关