1. 程式人生 > 其它 >super關鍵字詳解

super關鍵字詳解

super關鍵字詳解

程式碼示例:

Person類

    package com.han.jicheng;
    
    public class Person {
    
        protected String name = "zhangsan1";
    
        public Person() {
            System.out.println("Person無參執行了");
        }
    
        public void print(){
            System.out.println("Person");
        }
    
    }

Student類

    package com.han.jicheng;
    
    public class Student extends Person{
    
        private  String name = "zhangsan2";
    
        public Student() {
            super();//呼叫父類的構造器,必須在程式碼第一行
            //this("zhangsan");呼叫構造器必須在構造器的第一行,且父類的子類的構造器只能呼叫一個,不能同時呼叫
            System.out.println("Student無參執行了");
        }
    
        public Student(String name) {
            this.name = name;
        }
    
        public void test(String name){
            System.out.println(name);//zhangsan3
            System.out.println(this.name);//zhangsan2
            System.out.println(super.name);//zhangsan1
        }
    
        public void print(){
            System.out.println("Student");
        }
    
        public void test2(){
            print();//Student
            this.print();//Student
            super.print();//Person
        }
    }

Application類

    package com.han.jicheng;
    
    public class Application {
        public static void main(String[] args) {
            Student student = new Student();
            System.out.println("================================");
            student.test("zhangsan3");
            System.out.println("================================");
            student.test2();
        }
    }

super注意點:

1.super呼叫父類的構造方法,必須在構造方法的第一個;

2.super只能出現在子類的構造方法或者方法中;

3.super和this不能同時呼叫構造方法;

Vs this:

1.代表物件不同;

  this:本身呼叫的物件;

  super:代表父類物件的引用;

2.前提:

  this:沒有繼承也可以使用;

  super:必須在繼承關係中使用;

3.構造方法

  this():本類的構造

  super():父類的構造