Java中super和this的用法詳解
super 用法super關(guān)鍵字用來訪問父類內(nèi)容,具體用法可分為三種:1.子類的成員方法訪問父類的成員變量
public class Animal { public int age = 10;}class Dog extends Animal { public int age = 5; public void showAge() { System.out.println(super.age); }}
2.子類的成員方法訪問父類的成員方法
public class Animal { public void fn(){ System.out.println('父類Animal的方法'); }}class Dog extends Animal { @Override public void fn() { super.fn(); System.out.println('子類Dog的方法'); }}
3.子類的構(gòu)造方法訪問父類的構(gòu)造方法
public class Animal { public Animal() { System.out.println('父類Animal的構(gòu)造方法'); }}class Dog extends Animal { public Dog() { super(); System.out.println('子類Dog的構(gòu)造方法'); }}
this 用法this關(guān)鍵字用來訪問本類內(nèi)容,具體用法可分為三種:1.本類的成員方法訪問本類的成員變量
public class Dog extends Animal { public int age = 1; public void showAge() { int age = 3; System.out.println(age); System.out.println(this.age); }}
2.本類的成員方法訪問本類的另一成員方法
public class Dog extends Animal { public int age = 1; public void showAge() { int age = 3; System.out.println(age); System.out.println(this.age); } public void fn() { this.showAge(); }}
3.本類的構(gòu)造方法訪問本類的另一個(gè)構(gòu)造方法,此時(shí)this(…)調(diào)用必須放在這個(gè)構(gòu)造方法中的第一句,且只能使用一次
public class Dog extends Animal { public Dog() { this(2); System.out.println('無參構(gòu)造'); } public Dog(int age) { System.out.println(age); System.out.println('有參構(gòu)造'); }}
super和this內(nèi)存圖解
總結(jié)
到此這篇關(guān)于Java中super和this的用法的文章就介紹到這了,更多相關(guān)Java中super和this的用法內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML入門的常見問題(一)2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. PHP字符串前后字符或空格刪除方法介紹4. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過程5. jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄6. css進(jìn)階學(xué)習(xí) 選擇符7. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法8. 解析原生JS getComputedStyle9. Echarts通過dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖10. nestjs實(shí)現(xiàn)圖形校驗(yàn)和單點(diǎn)登錄的示例代碼
