温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Java中如何转换父类和子类

发布时间:2020-07-27 14:43:53 来源:亿速云 阅读:179 作者:小猪 栏目:编程语言

这篇文章主要讲解了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;
 
 }
}

Java中如何转换父类和子类

Java中如何转换父类和子类

可以看到,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中如何转换父类和子类有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI