Java 中的扩展转换(隐式)和缩窄转换(显式)有什么区别?
Java 中的**类型转换**用于将一种类型的对象或变量转换为另一种类型。当我们转换或分配一种数据类型到另一种数据类型时,它们可能不兼容。如果合适,它将顺利进行,否则可能会导致数据丢失。
Java 中的类型转换类型
Java 类型转换分为两种类型。
- 扩展转换(**隐式**)– 自动类型转换
- 缩窄转换(**显式**)– 需要显式转换
扩展转换(从小类型到大类型)
如果两种类型兼容且目标类型大于源类型,则可以发生**扩展类型转换**。当**两种类型兼容**且**目标类型大于源类型**时,就会发生扩展转换。
示例 1
public class ImplicitCastingExample {
public static void main(String args[]) {
byte i = 40;
// No casting needed for below conversion
short j = i;
int k = j;
long l = k;
float m = l;
double n = m;
System.out.println("byte value : "+i);
System.out.println("short value : "+j);
System.out.println("int value : "+k);
System.out.println("long value : "+l);
System.out.println("float value : "+m);
System.out.println("double value : "+n);
}
}输出
byte value : 40 short value : 40 int value : 40 long value : 40 float value : 40.0 double value : 40.0
类类型的扩展转换
在下面的示例中,我们正在将较小类型的**子类**分配给较大的类型的**父类**,因此不需要进行转换。
示例 2
class Parent {
public void display() {
System.out.println("Parent class display() called");
}
}
public class Child extends Parent {
public static void main(String args[]) {
Parent p = new Child();
p.display();
}
}输出
Parent class display() method called
缩窄转换(从大类型到小类型)
当我们将较大类型分配给较小类型时,需要进行**显式转换**。
示例 1
public class ExplicitCastingExample {
public static void main(String args[]) {
double d = 30.0;
// Explicit casting is needed for below conversion
float f = (float) d;
long l = (long) f;
int i = (int) l;
short s = (short) i;
byte b = (byte) s;
System.out.println("double value : "+d);
System.out.println("float value : "+f);
System.out.println("long value : "+l);
System.out.println("int value : "+i);
System.out.println("short value : "+s);
System.out.println("byte value : "+b);
}
}输出
double value : 30.0 float value : 30.0 long value : 30 int value : 30 short value : 30 byte value : 30
缩窄类类型
当我们将较大类型分配给较小类型时,我们需要**显式**地进行**类型转换**。
示例 2
class Parent {
public void display() {
System.out.println("Parent class display() method called");
}
}
public class Child extends Parent {
public void display() {
System.out.println("Child class display() method called");
}
public static void main(String args[]) {
Parent p = new Child();
Child c = (Child) p;
c.display();
}
}输出
Child class display() method called
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP