欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java中父類和子類之間的轉換操作示例

 更新時間:2020年05月13日 12:06:06   作者:Z_DZ  
這篇文章主要介紹了Java中父類和子類之間的轉換操作,結合實例形式分析了Java中父類和子類之間的轉換相關原理、操作技巧與使用注意事項,需要的朋友可以參考下

本文實例講述了Java中父類和子類之間的轉換操作。分享給大家供大家參考,具體如下:

一、父類引用強轉成為子類引用 

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 = "中國";
 }
 
 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()+"  我的國家是:"+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無法訪問子類中的特有的方法(父類引用可以訪問子類中重寫父類中的方法),但是強轉成為子類類型的引用c1之后,c1就可以訪問子類中所有的方法啦。

二、父類不可以強轉成為子類

package learn20180720;
public class TestPeCh {
 
 public static void main(String[] args) {
 // TODO Auto-generated method stub
 People p1 = new People();
 
 Chinese c1 = (Chinese)p1;
 
 }
}

報錯了!

更多關于java相關內容感興趣的讀者可查看本站專題:《Java面向對象程序設計入門與進階教程》、《Java數據結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總

希望本文所述對大家java程序設計有所幫助。

相關文章

最新評論