Java-Super
生活随笔
收集整理的這篇文章主要介紹了
Java-Super
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
super 調用父類屬性
public class Person {// public > protected > default > private// public// protected --受保護的,可以繼承// default -- 不寫就是默認,可以繼承// private -- 父類私有,(private 不能繼承,不能直接訪問,可以通過get set間接訪問 )protected String name = "Person.wang"; } public class Student extends Person{private String name = "Student.wang";public void test(String name){System.out.println(name); // 王System.out.println(this.name); // Student.wangSystem.out.println(super.name); // Person.wang}} public class Application {public static void main(String[] args) {Student student = new Student();student.test("王");} }super 調用父類方法
public class Person {protected String name = "Person.wang";public void print(){System.out.println("Person");} } public class Student extends Person{private String name = "Student.wang";public void print(){System.out.println("Student");}public void test1() {print(); // Studentthis.print(); // Studentsuper.print(); // Person} } public class Application {public static void main(String[] args) {Student student = new Student(); // student.test("王");student.test1();} }private 私有的無法被繼承,使用super也不能調用
super與構造函數
public class Person {public Person() {System.out.println("Person無參執行了");} } public class Student extends Person{public Student() {// 隱藏代碼: 調用了父類的無參構造,super();寫不寫都行 // super(); // 調用父類構造器,必須要在子類構造器的第一行// this(""); // 調用構造器,必須要在第一行System.out.println("Student無參執行了");} } public class Application {public static void main(String[] args) {Student student = new Student();} } super注意點:1. super 調用父類的構造方法,必須在構造方法的第一個2. super 必須只能出現在子類的方法或者構造方法中3. super和this 不能同時調用構造方法!因為他們都要寫在方法的第一行 VS this:代表的對象不同:this: 本身調用著的這個對象super: 代表父類對象的應用前提this: 沒有繼承也可以使用super: 只能在繼承條件才可以使用構造方法:this() ; 本類的構造super(); 父類的構造https://www.bilibili.com/video/BV12J41137hu?p=69
總結
以上是生活随笔為你收集整理的Java-Super的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript从入门到放弃 - (
- 下一篇: Java-数组的使用