super详解

继承

  • object类
  • super - this

Application类:

package oop.demo06;

import oop.demo06.Student;

public class Application02 {
    public static void main(String[] args) {
        Student student = new Student();
        /*
        如果只有上面Student student = new Student();这句话,
        输出: Person无参执行了
              Student无参执行了
        为什么只new了Student,会输出父类Person的东西,因为
        有一句隐藏代码super();
         */


        student.test("冰默");

        System.out.println("--------------------");

        student.test1();

    }
}

输出:

在这里插入图片描述

Person类:

package oop.demo06;

public class Person {

    public Person(String name) {
        System.out.println("Person无参执行了");
    }

    protected String name = "LH";

    //private私有的东西无法被继承,super也不行!
    public void print(){
        System.out.println("Person");
    }
}

Student类:

package oop.demo06;

public class Student extends Person {

    public Student() {
        //隐藏代码:默认调用了父类的无参构造
        super("name");//调用父类的构造器,必须要在子类构造器的第一行
        System.out.println("Student无参执行了");
    /*
    如果父类中没有无参构造,设置了有参构造,那么子类也不能设置无参构造
    一般父类设置了有参构造,都会显示的写出无参构造
    如果执意要调用没有无参构造只有有参构造的的父类,就要显示的调用有参构造
    如:super("name");
     */
    }
    private String name = "boom";

    public void print(){
        System.out.println("Student");
    }

    public void test1(){
        print();//Student
        this.print();//Student
        super.print();//Person
    }


    public void test(String name){
        System.out.println(name);//冰默
        System.out.println(this.name);//boom
        System.out.println(super.name);//LH
    }


}
super注意点:
    1.super调用父类的构造方法,必须在构造方法的第一个!
    2.super必须只能出现在子类的方法或者构造方法中!
    3.superthis 不能同时调用构造方法!

superthis对比:
    代表的对象不同:
        this:本身调用者这个对象
        super: 代表父类对象的引用
    前提
        this:没有继承也可以使用
        super:只能在继承条件下可以使用
    构造方法
        this();本类的构造
        super();父类的构造

this和super关键字的区别

  • 方法重写
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值