java - 扩大/缩小转换的实际应用?

标签 java c++ casting

有人可以解释一下为什么您会使用扩大或缩小转换吗?我已经阅读了很多关于这些的内容,但没有人给我一个实际的例子。谢谢!

最佳答案

(Java) 扩大和缩小转换与相关类型之间的转换有关。以抽象(超)类与其(子)子类之间的关系为例;让我们使用 java.lang.Number 类(抽象)和一个直接子类 Integer。我们有:

(superclass)                               Number
                                   __________/\__________
                                  /       |      |       \
(concrete subclasses)          Integer   Long    Float   Double

扩大转换:如果我们采用特定类型(子类)并尝试将其分配给不太特定的类型(父类(super class)),则会发生这种情况。

Integer i = new Integer(8);
Number n = i;   // this is widening conversion; no need to cast

缩小转换:发生在我们采用不太具体的类型(父类(super class))并尝试将其分配给更具体的类型(子类)时,这需要显式转换。

Number n = new Integer(5); // again, widening conversion
Integer i = (Integer) n;   // narrowing; here we explicitly cast down to the type we want - in this case an Integer

您需要注意某些问题,例如 ClassCastExceptions:

Integer i = new Integer(5);
Double d = new Double(13.3);
Number n;

 n = i; // widening conversion - OK
 n = d; // also widening conversion - OK

 i = (Integer) d;  // cannot cast from Double to Integer - ERROR

 // remember, current n = d (a Double type value)
 i = (Integer) n;  // narrowing conversion; appears OK, but will throw ClassCastException at runtime - ERROR

处理此问题的一种方法是使用带有 instanceof 关键字的 if 语句:

 if( n instanceof Integer) {
      i = (Integer) n;
 }

为什么要使用它?假设你正在为某个程序建立人员层次结构,你有一个名为“Person”的通用父类(super class),它以名字和姓氏作为参数,还有子类“Student”、“Teacher”、“Secretary”等。这里您最初可以创建一个通用人,并将其(通过继承)分配给一个 Student,该 Student 将在其构造函数中设置一个额外的 studenID 变量字段。您可以使用一个将更通用(更广泛)的类型作为参数的方法,并处理该类型的所有子类:

 public static void main(String[] args) {
     Person p = new Student("John", "Smith", 12345);
     printInfo(p);
 }

 // this method takes the wider Person type as a parameter, though we can send it a narrower type such as Student if we want
 public static void printInfo(Person p) {
     System.out.println("First: " + p.getFirstName());
     System.out.println("Last: " + p.getLastName());
     if (p instanceof Student) {
         System.out.println( (Student)p).getStudentID() );  // we cast p to Student with Narrow Conversion which allows us to call the getStudentID() method; only after ensuring the p is an instance of Student
     }
}

我意识到这可能不是处理事情的理想方式,但为了演示起见,我认为它可以展示一些可能性。

关于java - 扩大/缩小转换的实际应用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16781649/

相关文章:

c++ - 无法打开共享对象文件 libmysqlclient.so.18

java - Groovy 调用 Java 库的方法没有签名

java - 将错误类型的对象放入 Map 中

java - 元素不会从列表中删除

java - 将 Velocity 配置为在未定义的 $variable 上失败

c++ - Friend 模板函数上 undefined reference

c# - FxCop 对如何消除多余的 castclass 感到困惑

Java - 方法与构造函数参数

java - 在 JTable 中设置单元格值时出现 ArrayIndexOutOfBounds

c++ - 如何在 rxcpp 自定义运算符中正确推断泛型