java中的super和this

super和this的含义
super :代表父类的存储空间标识(可以理解为父亲的引用)。
this :代表当前对象的引用(谁调用就代表谁)。
super和this的用法
1. 访问成员
this.成员变量 ‐‐ 本类的 super.成员变量 ‐‐ 父类的
this.成员方法名() ‐‐ 本类的 super.成员方法名() ‐‐ 父类的
用法演示,代码如下:

class Animal {
    public void eat() {
        System.out.println("animal : eat");
    }
}
class Cat extends Animal {
    public void eat() {
        System.out.println("cat : eat");
    }
    public void eatTest() {
        this.eat();   // this  调用本类的方法
        super.eat();  // super 调用父类的方法
    }
}
public class ExtendsDemo08 {
    public static void main(String[] args) {
        Animal a = new Animal();
        a.eat();
        Cat c = new Cat();
        c.eatTest();
    }
}
/*输出结果为:
animal : eat
cat : eat
animal : eat*/
  1. 访问构造方法
    this(...) ‐‐ 本类的构造方法 super(...) ‐‐ 父类的构造方法
    子类的每个构造方法中均有默认的super(),调用父类的空参构造。手动调用父类构造会覆盖默认的super()。super() 和 this() 都必须是在构造方法的第一行,所以不能同时出现。
发布了32 篇原创文章 · 获赞 28 · 访问量 1333

猜你喜欢

转载自blog.csdn.net/weixin_42369886/article/details/104456279