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ú)法訪問子類中的特有的方法(父類引用可以訪問子類中重寫父類中的方法),但是強(qiáng)轉(zhuǎn)成為子類類型的引用c1之后,c1就可以訪問子類中所有的方法啦。
二、父類不可以強(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. 簡(jiǎn)述JAVA同步、異步、阻塞和非阻塞之間的區(qū)別2. 使用Python3 poplib模塊刪除服務(wù)器多天前的郵件實(shí)現(xiàn)代碼3. Python TestSuite生成測(cè)試報(bào)告過程解析4. 在JSP中使用formatNumber控制要顯示的小數(shù)位數(shù)方法5. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析6. 深入了解JAVA 軟引用7. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題8. 詳解JAVA 強(qiáng)引用9. SpringBoot集成mqtt的多模塊項(xiàng)目配置詳解10. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法
