super和this的区别和使用

super

  • 注意点:

  1. super调用父类的构造方法,必须在子类构造方法的第一行;

  2. super必须只能出现在子类的方法或者构造方法中;

  3. super和this不能同时调用构造方法;

  4. 调用方法时先调用构造方法,顺序是先执行父类的构造方法,再执行子类的构造方法。

  • 对比this的区别:

  1. 代表的对象不同:this调用的是对象;super是调用的父类

  2. 前提不一致:this没有继承也可以使用,而super只能在继承条件下才能使用

  3. 构造方法的区别:this()调用的是本类的构造;super()调用的是父类的构造

package com.oop;

import com.oop.demo03.Student;
import com.oop.demo03.Teacher;

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


package com.oop.demo03;
//在java中,所有的类,都默认直接或间接继承object类
//person 人
public class Person {
    public Person() {
        System.out.println("Person无参执行了");
    }

    protected String name="yanyun";
    public void print(){
        System.out.println("Person");
    }
}


package com.oop.demo03;
public class Student extends Person {
    public Student() {
        System.out.println("Student无参执行了");
    }

    private String name="cyy";
    public void print(){
        System.out.println("Student");
    }
    public void test1(){
       print();
       this.print();
       super.print();
    }

 

 

 

 

posted @ 2022-04-15 20:11  胖虎9  阅读(465)  评论(0编辑  收藏  举报