Java中的super是什么?
java中的super關鍵字是一個引用變量,用於引用父類對象。關鍵字“super”以繼承的概念出現在類中。主要用於以下情況:
1.使用super與變量:
當派生類和基類具有相同的數據成員時,會發生此情況。在這種情況下,JVM可能會模糊不清。我們可以使用以下代碼片段更清楚地理解它:
/* Base class vehicle */ class Vehicle { int maxSpeed = 120; } /* sub class Car extending vehicle */ class Car extends Vehicle { int maxSpeed = 180; void display() { /* print maxSpeed of base class (vehicle) */ System.out.println("Maximum Speed: " + super.maxSpeed); } } /* Driver program to test */ class Test { public static void main(String[] args) { Car small = new Car(); small.display(); } }
輸出:
Maximum Speed: 120
在上面的例子中,基類和子類都有一個成員maxSpeed。我們可以使用super關鍵字訪問sublcass中的基類的maxSpeed。
2.使用super方法:
當我們要調用父類方法時使用。所以,無論何時,父類和子類都具有相同的命名方法,那么為了解決歧義,我們使用super關鍵字。這段代碼有助於理解super關鍵字的使用情況。
/* Base class Person */ class Person { void message() { System.out.println("This is person class"); } } /* Subclass Student */ class Student extends Person { void message() { System.out.println("This is student class"); } // Note that display() is only in Student class void display() { // will invoke or call current class message() method message(); // will invoke or call parent class message() method super.message(); } } /* Driver program to test */ class Test { public static void main(String args[]) { Student s = new Student(); // calling display() of Student s.display(); } }
輸出:
This is student class This is person class
在上面的例子中,我們已經看到,如果我們只調用方法message(),那么當前的類message()被調用,但是使用super關鍵字時,超類的message()也可以被調用。
3.使用超級構造函數:
super關鍵字也可以用來訪問父類的構造函數。更重要的是,'超'可以根據情況調用參數和非參數構造函數。以下是解釋上述概念的代碼片段:
/* superclass Person */ class Person { Person() { System.out.println("Person class Constructor"); } } /* subclass Student extending the Person class */ class Student extends Person { Student() { // invoke or call parent class constructor super(); System.out.println("Student class Constructor"); } } /* Driver program to test*/ class Test { public static void main(String[] args) { Student s = new Student(); } }
輸出:
Person class Constructor Student class Constructor
在上面的例子中,我們通過子類構造函數使用關鍵字'super'調用超類構造函數。
其他要點:
1.調用super()必須是類構造函數中的第一條語句。
2.如果構造函數沒有明確調用超類構造函數,那么Java編譯器會自動向超類的無參構造函數插入一個調用。如果超類沒有沒有參數的構造函數,你會得到一個編譯時錯誤。對象 確實有這樣的構造函數,所以如果Object是唯一的超類,那就沒有問題了。
3.如果子類構造函數調用其超類的構造函數,無論是顯式還是隱式調用,您都可能認為調用了整個構造函數鏈,並返回到Object的構造函數。事實上,情況就是如此。它被稱為構造函數鏈。