public class Test {
public static void main(String[] args) {
Person person = new Boy();
Boy boy = (Boy) person;
boy.eat();
}
class Person {
public void eat() {
System.out.println("The people were eating");
}
}
class Boy extends Person {
public void eat() {
System.out.println("The boy were eating");
}
}
打印结果:The boy were eating
原因:当Boy实例化后将引用地址返回传给person,这时person引用实际指向的是Boy,所以将person转换成Boy能成功。
再定义一个类:
class Girl extends Person {
public void eat() {
System.out.println("The girl were eating");
}
}
main方法中添加:
Person p = new Girl();
Boy b = (Boy)p;
b.eat();
运行时提示:Girl cannot be cast to Boy(不能将女孩转换成男孩)
原因:当Girl实例化后将引用地址返回传给p,这时p引用实际指向的是Girl,将p转换成Boy也就是说将Girl转换成Boy,肯定不能成功。
上面的例子换句话来说,男孩和女孩都是人这肯定是对的,但你要说女孩是男孩肯定是不对的。
父类转子类的
前提
是:此父类对象为子类对象的引用
例如:
Father father = (Father)son;
当这种情况时,可以用instanceof判断是否是子类类型(实际) 然后强转回去
if(father instanceof Son)
Son son =(Son)father;
除此之外,不行。
Java中父类强制转换成子类的原则:父类型的引用指向的是哪个子类的实例,就能转换成哪个子类的引用。例:public class Test { public static void main(String[] args) { Person person = new Boy(); Boy boy = (Boy) person; boy.eat(); }
try {
Object objectBigCar = Class.forName( new BigCar().getClass().getName() ).newInstance();
BigCar bigCar2 = ( BigCar )objectBigCar;
bigCar2.setLength( 200 )...
Student s=p; //错误
3.只有
父类
对象指向
子类
,那么
父类
是可以
强制转换
成
子类
,如果
父类
对象没有指向
子类
,那么
强制转换
就会报错的
Person p=new Person();
Student s=new Student();
s=(stud.
父类
转
子类
假设Person类为
父类
,Student类为
子类
,
子类
方法为go(),此时
父类
实例化
子类
对象想调用
子类
方法是无法直接调用的,需要
强制转换
为
子类
方法如下:
子类
转
父类
>
子类
转换
父类
:可能会丢失自己本来的方法
假设Person类为
父类
,Student类为
子类
,
子类
方法为go(),此时
子类
类实例化对象想转换为
父类
,则转换后则无法调用go()方法
示例如下:
今天重构QT控件获得焦点的函数时,需要将基类传化为
子类
,尝试过一些办法后
成
功,记录一下。
1.
子类
向基类(向上强制类型转换)
切割:覆盖方法和
子类
数据丢失的现象生
成
切割(slice)。
下面套用一个别人的例子
#include "stdafx.h"
#include
using namespace std;
class Base
public:
2.
Java
继承
继承就是
子类
继承
父类
的特征和行为,使得
子类
对象(实例)具有
父类
的实例域和方法,或
子类
从
父类
继承方法,使得
子类
具有
父类
相同的行为。
Java
子类
强转
父类
父类
引用指向
子类
对象:
java
中
子类
强转
父类
,实际上依然是
子类
;
该引用只能调用
父类
中
定义的方法和变量;
如果
子类
中
重写了
父类
中
的一个方法,那么在调用这个方法
现在有2个类,Father、Son,如何快速的将Father的所有属性复制到Son。
现实业务需求:假定有个表User,现在进行分页查询,但是单单User表
中
的信息无法满足业务需求,如:需要加入行号、需要对性别字段sex进行转义。则可定义一个
子类
UserVo,在
子类
中
添加对应的属性。
最快捷的方式:使用spring的BeanUtils
import lombok.Data;
import org.springframework.beans.BeanU...
二、基本类型 转换
原则
1、类型转换主要在在 赋值、方法调用、算术运算 三种情况下发生。
a、赋值和方法调用 转换规则:从低位类型到高位类型自动转换;从高位类型到低位类型需要强制类型转换:
(1)布尔型和其它基本数据类型之间不能相互转换;
(2)byte型可以转换为short、int、、long、float和double;
(3)short可转换为int、long、float和double;
(4)char可转换为int、long、float和dou
List<B> dadList = new ArrayList<B>();
for(A a : childList){
dadList.add(a); //依次加到
父类
List里
二、
父类
转
子类
List<B> dadList = getxxxxxx;
List<A> chil
SpringCloud-Finchley.SR1版本中 hystrix-dashboard 报错 /actuator/hystrix.stream 404 Not Found
qq_34023259: