Java super关键字

Java super关键字

super:表示父类中的内容

定义一个父类:Fruit

package com.wq.entity;
/**
 * @author WangQi
 * @date 2020/4/1 0:16
 */
public class Fruit {
    String name = "梨子";
}

定义一个子类:Apple

package com.wq.entity;

/**
 * @author WangQi
 * @date 2020/4/1 0:19
 */
public class Apple extends Fruit{
    String name = "红富士";
    public void eat(){
        System.out.println("我喜欢吃"+this.name);
        //super调用父类中的内容
        System.out.println("我喜欢吃"+super.name);
    }
}

在测试文件中调用eat

package com.wq.entity;
/**
 * @author WangQi
 * @date 2020/4/1 0:20
 */
public class TextSuper {
    public static void main(String[] args) {
        Apple a1 = new Apple();

        a1.chi();

    }
}

其中super调用的是父类中的内容

System.out.println("我喜欢吃"+this.name);
//super调用父类中的内容
System.out.println("我喜欢吃"+super.name);

运行结果就是:

我喜欢吃红富士
我喜欢吃梨子

总结

super用于区别父类和子类中重名的内容

posted @ 2020-04-01 22:47  waitly  阅读(9)  评论(0)    收藏  举报  来源