学习笔记---super详解

super详解

  1. 用法:
  • super用于引用父类的属性或方法,super.xxx与this.xxx相对应
  • 子类无参构造器中有一句隐藏代码:调用父类无参构造器
  • 若显示地调用该父类无参构造器super(),必须放在子类构造器的第一行
  1. 注意点:
  • super调用父类的构造方法,必须在子类构造方法的第一行
  • super只能出现在子类的方法或构造方法中
  • super和this不能同时调用构造方法
  1. 和this的区别:
  • 代表的对象不同
    • this:本身这个类的对象
    • super:代表父类对象的引用
  • 前提
    • this:没有继承父类也能使用
    • super:只能在继承条件中使用
  • 构造方法
    • this():本类的构造
    • super():父类的构造

代码示例:

package oop.Demo04;

public class Student extends Person{
    
    
    private String name = "小明";

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

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

    public void test2(){
    
    
        print();    //Student
        this.print();   //Student
        super.print();  //Person
    }
    public void test1(String name){
    
    
        System.out.println(name);   //java
        System.out.println(this.name);      //小明
        System.out.println(super.name);     //xiaoming
    }
}
//快捷键:crtl + h
/*
        Student student = new Student();
        student.say();
        System.out.println(student.getMoney());
 */
package oop.Demo04;

public class Person {
    
    
    public String name = "xiaoming";

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

    public void print(){
    
    
        System.out.println("Person");
    }
}
package oop;

import oop.Demo04.Student;

public class Application {
    
    
    public static void main(String[] args) {
    
    
        Student student = new Student();
        /*
        Person无参执行了
        Student无参执行了
         */
        //student.test1("java");
        //student.test2();
    }
}

猜你喜欢

转载自blog.csdn.net/yang862819503/article/details/113731778
今日推荐