Java中父類和子類之間的轉(zhuǎn)換操作示例
本文實(shí)例講述了Java中父類和子類之間的轉(zhuǎn)換操作。分享給大家供大家參考,具體如下:
一、父類引用強(qiáng)轉(zhuǎn)成為子類引用package learn20180720; public class People { private String name; private Integer age; private Double height; public People(){ this.name = ''; this.age = 0 ; this.height = 0.0; } public People(String name, Integer age, Double height) { super(); this.name = name; this.age = age; this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public void tellObjectName(People p) { System.err.println(p.name); } public void sayInformation() { System.err.println('我的名字叫做:'+this.name+'我的年齡是:'+this.age+'我的身高是'+this.height); }}
package learn20180720;public class Chinese extends People{ private String country; public Chinese(){ super(); country = ''; } public Chinese(String aname,Integer aage,Double aheight) { super(aname,aage,aheight); this.country = '中國(guó)'; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public void sayInformation() { // TODO Auto-generated method stub System.err.println('我的名字叫做:'+this.getName()+' 我的年齡是:'+this.getAge()+' 我的身高是:'+this.getHeight()+' 我的國(guó)家是:'+this.country); }}
package learn20180720;public class TestPeCh { public static void main(String[] args) { // TODO Auto-generated method stub People p1 = new Chinese(); Chinese c1 = (Chinese)p1; }}
可以看到,p1無(wú)法訪問(wèn)子類中的特有的方法(父類引用可以訪問(wèn)子類中重寫父類中的方法),但是強(qiáng)轉(zhuǎn)成為子類類型的引用c1之后,c1就可以訪問(wèn)子類中所有的方法啦。
二、父類不可以強(qiáng)轉(zhuǎn)成為子類package learn20180720;public class TestPeCh { public static void main(String[] args) { // TODO Auto-generated method stub People p1 = new People(); Chinese c1 = (Chinese)p1; }}
報(bào)錯(cuò)了!
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java面向?qū)ο蟪绦蛟O(shè)計(jì)入門與進(jìn)階教程》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章:
1. Python實(shí)現(xiàn)學(xué)生管理系統(tǒng)的代碼(JSON模塊)2. Java類加載機(jī)制實(shí)現(xiàn)步驟解析3. JAMon(Java Application Monitor)備忘記4. Python OpenCV去除字母后面的雜線操作5. Spring security 自定義過(guò)濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)6. IntelliJ IDEA設(shè)置背景圖片的方法步驟7. Python os庫(kù)常用操作代碼匯總8. Python TestSuite生成測(cè)試報(bào)告過(guò)程解析9. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法10. 增大python字體的方法步驟
