Java 中的向上装箱和向下装箱是什么?


类型强制转换是将一个数据类型转换为另一种数据类型。

向上强制转换 - 将子类类型转换为超类类型称为向上强制转换。

示例

class Super {
   void Sample() {
      System.out.println("method of super class");
   }
}

public class Sub extends Super {
   void Sample() {
      System.out.println("method of sub class");
   }
   
   public static void main(String args[]) {
      Super obj =(Super) new Sub(); obj.Sample();
   }
}

向下强制转换 - 将超类类型转换为子类类型称为向下强制转换。

示例

class Super {
   void Sample() {
      System.out.println("method of super class");
   }
}

public class Sub extends Super {
   void Sample() {
      System.out.println("method of sub class");
   }

   public static void main(String args[]) {
      Super obj = new Sub();
      Sub sub = (Sub) obj; sub.Sample();
   }
}


更新于: 2020 年 2 月 18 日

1000 多次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.