Java--类型转化

来源:互联网 发布:宝宝生长曲线图软件 编辑:程序博客网 时间:2024/06/13 06:41

Java类型转化(Implementing type casting)


一、原始数据类型转换(Type Casting primitive data types)


1.隐式转换Implict Casting refers to an automatic conversion of one data type into anther.)

int a = 100;long b = a;

2.式转换Explict Casting occurs when one data type cannot be implicitly converted into anther data type.)

int a = 10;byte b = (byte) a;System.out.println(b);

二、对象类型转换(Type Casting Object)


举个例子:有2个类,Father是父类,Son类继承自Father。

Father f1 = newSon(); // 这就叫 upcasting (向上转型)// 现在f1引用指向一个Son对象

Son s1 = (Son)f1; // 这就叫 downcasting (向下转型)// 现在f1还是指向Son对象第2个例子:Father f2 = new Father();Son s2 = (Son)f2; // 出错,子类引用不能指向父类对象

你或许会问,第1个例子中:Son s1 = (Son)f1;问什么 是正确的呢。很简单因为f1指向一个子类对象,Father f1 = new Son(); 子类s1引用当然可以指向子类对象了。而f2 被传给了一个Father对象,Fatherf2 = new Father();子类s1引用不能指向父类对象。

总结:1。父类引用指向子类对象,而子类引用不能指向父类对象。2。把子类对象直接赋给父类引用叫upcasting向上转型,向上转型不用强制转换。如:Father f1 = new Son();3。把指向子类对象的父类引用赋给子类引用叫向下转型(downcasting),要强制转换。如:f1 就是一个指向子类对象的父类引用。把f1赋给子类引用s1即 Son s1 = (Son)f1;其中f1前面的(Son)必须加上,进行强制转换。

---------------------------------------------

1.向上转化Upcasting

2.向下转化Downcasting)

0 0
原创粉丝点击