Java 中的扩展类型转换(隐式)和收缩类型转换(显式)有什么区别?

javaobject oriented programmingprogramming更新于 2024/7/26 23:08:00

Java 中的类型转换用于将一种类型的对象或变量转换为另一种类型。当我们将一种数据类型转换或分配给另一种数据类型时,它们可能不兼容。如果合适,那么它会顺利完成,否则可能会丢失数据。

Java 中的类型转换类型

Java 类型转换分为两种类型。

  • 扩展类型转换(隐式) - 自动类型转换
  • 收缩类型转换(显式) -需要显式转换

扩展转换(从较小类型到较大类型)

扩展 类型转换可能发生在两种类型兼容且目标类型大于源类型的情况下。当两种类型兼容目标类型大于源类型时,会发生扩展转换。

示例 1

public class ImplicitCastingExample {
   public static void main(String args[]) {
      byte i = 40;
      // 以下转换无需转换
      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;
      // 以下转换需要显式转换
      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

相关文章