Java中父类和子类之间的转换操作示例
时间:2021-06-03 09:08:26|栏目: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节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。
上一篇:java 异常的实例详解
栏 目:JAVA代码
本文标题:Java中父类和子类之间的转换操作示例
本文地址:http://www.codeinn.net/misctech/134068.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




