Java中super和this的用法詳解
super 用法super關(guān)鍵字用來(lái)訪(fǎng)問(wèn)父類(lèi)內(nèi)容,具體用法可分為三種:1.子類(lèi)的成員方法訪(fǎng)問(wèn)父類(lèi)的成員變量
public class Animal { public int age = 10;}class Dog extends Animal { public int age = 5; public void showAge() { System.out.println(super.age); }}
2.子類(lèi)的成員方法訪(fǎng)問(wèn)父類(lèi)的成員方法
public class Animal { public void fn(){ System.out.println('父類(lèi)Animal的方法'); }}class Dog extends Animal { @Override public void fn() { super.fn(); System.out.println('子類(lèi)Dog的方法'); }}
3.子類(lèi)的構(gòu)造方法訪(fǎng)問(wèn)父類(lèi)的構(gòu)造方法
public class Animal { public Animal() { System.out.println('父類(lèi)Animal的構(gòu)造方法'); }}class Dog extends Animal { public Dog() { super(); System.out.println('子類(lèi)Dog的構(gòu)造方法'); }}
this 用法this關(guān)鍵字用來(lái)訪(fǎng)問(wèn)本類(lèi)內(nèi)容,具體用法可分為三種:1.本類(lèi)的成員方法訪(fǎng)問(wèn)本類(lèi)的成員變量
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.本類(lèi)的成員方法訪(fǎng)問(wèn)本類(lèi)的另一成員方法
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.本類(lèi)的構(gòu)造方法訪(fǎng)問(wèn)本類(lèi)的另一個(gè)構(gòu)造方法,此時(shí)this(…)調(diào)用必須放在這個(gè)構(gòu)造方法中的第一句,且只能使用一次
public class Dog extends Animal { public Dog() { this(2); System.out.println('無(wú)參構(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. Python網(wǎng)絡(luò)編程之ZeroMQ知識(shí)總結(jié)2. chat.asp聊天程序的編寫(xiě)方法3. python基于tkinter點(diǎn)擊按鈕實(shí)現(xiàn)圖片的切換4. .NET 中配置從xml轉(zhuǎn)向json方法示例詳解5. Python TestSuite生成測(cè)試報(bào)告過(guò)程解析6. python之cur.fetchall與cur.fetchone提取數(shù)據(jù)并統(tǒng)計(jì)處理操作7. Python查找算法之分塊查找算法的實(shí)現(xiàn)8. 解決AJAX返回狀態(tài)200沒(méi)有調(diào)用success的問(wèn)題9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案
