this和super的区别
this
this是当前对象的引用,指向了这个类类的对象。作用:
1.可以调用类中成员的属性。
方式:class student{
private int age;
private String name;
}
//含参的构造方法
public student (int age ,String name){
this.age=age;
this.name=name;
}
//当传入参数的名字与成员属性的名字相同时,this有效的防止参数自己给自己赋值。
2.可以调用类中的方法
class student{
private int age;
private String name;
public student(int age,String name){
this.age=age;
this.name=name;
}
public void eat(){
System.out.println(this.name+"在吃饭");
}
public void show(){
this.eat();
}
}
3.调用自身构造方法
:必须放在第一行,且只能调用一个构造方法,且只能在构造方法中通过this调用构造方法,不能再普通方法中。
this是一个引用: 在这个构造方法中,使用了this关键字,此时对象还没有构造好,this代表当前对象的引用。
class student{
private int age;
private String name;
public student(){
this(15,"zhangsan");
}
//这两个构造方法的关系为重载
public student(int age,String name){
this.age=age;
this.name=name;
}
}
super
super代表所继承的父类的引用。用法:
1.使用super来调用父类的构造方法
public Bird(String name) {
super(name);
}
2.使用super来调用父类的普通方法
public class Bird extends Animal {
public Bird(String name) {
super(name);
}
@Override
public void eat(String food) {
super.eat(food);
System.out.println("我是一只小鸟");
System.out.println(this.name + "正在吃" + food);
}
}
总结:
this访问的是本类的属性和方法,super访问的是父类的属性和方法;
访问时this会先查找本类,如果本类没有,才会去访问父类,而super直接访问调用父类;
this代表当前对象的引用,super不能;
this调用本类构造方法,必须放在本类构造方法的第一行,super调用父类构造方法,放在字类的构造方法首行。
在对拥有父类的子类进行初始化时,父类的构造方法也会执行,且优先于子类的构造函数执行;因为每一个子类的构造函数中的第一行都有一条默认的隐式语句super()
this(参数)和super(参数)不能同时出现在构造方法当中
this和super不能用于static修饰的变量,方法,代码块;因为this和super都是指的是对象(实例),而static和对象无关。