Java-Super

super 调用父类属性

public class Person {
    // public > protected > default > private
    // public
    // protected  --受保护的,可以继承
    // default  -- 不写就是默认,可以继承
    // private  -- 父类私有,(private 不能继承,不能直接访问,可以通过get set间接访问 )

    protected String name = "Person.wang";
}
public class Student extends Person{

    private String name = "Student.wang";

    public void test(String name){
        System.out.println(name); // 王
        System.out.println(this.name);  // Student.wang
        System.out.println(super.name);  // Person.wang
    }

}
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
        student.test("王");
    }
}

在这里插入图片描述

super 调用父类方法

public class Person {
    protected String name = "Person.wang";
    public void print(){
        System.out.println("Person");
    }
}
public class Student extends Person{

    private String name = "Student.wang";

    public void print(){
        System.out.println("Student");
    }
    public void test1() {
        print(); // Student
        this.print();  // Student
        super.print();  // Person
    }
}
public class Application {
    public static void main(String[] args) {
        Student student = new Student();
//        student.test("王");
        student.test1();
    }
}

在这里插入图片描述

private 私有的无法被继承,使用super也不能调用
在这里插入图片描述

super与构造函数

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

public class Student extends Person{
    public Student() {
        // 隐藏代码: 调用了父类的无参构造,super();写不写都行
//        super(); // 调用父类构造器,必须要在子类构造器的第一行
        //        this(""); // 调用构造器,必须要在第一行
        System.out.println("Student无参执行了");
    }
}

public class Application {
    public static void main(String[] args) {
        Student student = new Student();
    }
}

在这里插入图片描述

super注意点:
		1. super 调用父类的构造方法,必须在构造方法的第一个
		2. super 必须只能出现在子类的方法或者构造方法中
		3. super和this 不能同时调用构造方法!因为他们都要写在方法的第一行
VS this:
		代表的对象不同:
				this: 本身调用着的这个对象
				super: 代表父类对象的应用
		前提
				this: 没有继承也可以使用
				super: 只能在继承条件才可以使用
		构造方法:
				this() ; 本类的构造
				super(); 父类的构造

https://www.bilibili.com/video/BV12J41137hu?p=69

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值