Day7-9 Super详解

Super详解

注意点:

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

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

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

vs this:

  1. 代表的对象不同

    this:本身调用者这个对象

    super:代表父类对象的引用

  1. 前提:

    this:没有继承也可以使用

    super:只能在继承条件下才可以使用

  1. 构造方法:

    this(): 本类的构造

    super(): 父类的构造

 
package com.oop.demo05;
 //Person 类   父类
 //在Java中,所有类都默认直接或间接继承Object类
 public class Person {
     //public     公有
     //private    私有  私有方法无法被子类继承
     //default    默认
     //protected  受保护的
 ​
 ​
     public Person() {
         System.out.println("Person无参构造执行了");
     }
 ​
     protected String name="kuangshen";
 ​
     public void print(){
         System.out.println("Person");
     }
 ​
 }

 

 
package com.oop.demo05;
 //Student 继承 Person,派生类,子类
 //子类继承父类,会拥有父类的全部方法
 public class Student extends Person {
     //ctrl+h  类的继承树
public Student() {
         //隐藏代码:super()  调用了父类的无参构造
         super();//调用父类构造器,必须在子类构造器第一行
         System.out.println("Student无参构造执行了");
     }
 ​
     private String name="qinjiang";
 ​
     public void test(String name){
         System.out.println(name);
         System.out.println(this.name);
         System.out.println(super.name);
     }
 ​
     public void print(){
         System.out.println("Student");
     }
 ​
     public void test1(){
         print();
         this.print();
         super.print();
 ​
     }
 }

 

 package com.oop;
 ​
 import com.oop.demo05.Student;
 ​
 public class Application {
     public static void main(String[] args) {
         Student student = new Student();
         student.test("秦疆");
         student.test1();
     }
 ​
 }

 

 
posted @ 2022-11-17 16:53  actadams68  阅读(44)  评论(0)    收藏  举报