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;

	}
	


}

 

 

报错了!

 

 

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值