Reglas de reducción de objetos en Java

Typecasting es uno de los conceptos más importantes que básicamente se ocupa de la conversión de un tipo de datos a otro tipo de datos implícita o explícitamente. En este artículo, se analiza el concepto de reducción de objetos. Está colocando la variable de referencia del padre que contiene el objeto del hijo en la variable de referencia del hijo. El downcasting no puede ser implícito. La sintaxis de downcasting es:

Type_A ref1 = new Type_B();
Type_C ref2 = (Type_D) ref1;

En esta sentencia se realizan dos operaciones:

  1. convertir un objeto referido por ref1 al tipo D
  2. asignar este objeto convertido de tipo D a una variable de referencia de tipo C

Hay 3 reglas que se comprueban si el downcasting tendrá éxito o no. Las reglas son las que se describen a continuación:

1. Verifique la conversión válida

Para que la conversión sea válida, el Tipo A y el Tipo D deben tener una relación entre ellos. Esta relación puede ser el tipo A es el padre del tipo D, o el tipo D es el padre del tipo A o el tipo A = tipo D. Si no existe tal relación, habrá un error en tiempo de compilación. El compilador verifica esta regla y, por lo tanto, no considera el tipo de objeto creado en ref1, es decir, solo considera el tipo A y el tipo D, no el tipo B (que es el tipo real de objeto de tiempo de ejecución creado). Teniendo en cuenta esta regla, veamos algunas afirmaciones que cumplen los criterios.

Object ref1 = new String();
String ref2 = (String) ref1; // satisfy rule 1
ref1 is of Object type which is parent of String

Object ref1 = new String();
Integer ref2 = (Integer) ref1 ; // satisfy rule 1
ref1 is of Object type which is parent of Integer

String ref1 = new String();
String ref2 = (String) ref1 ; // satisfy rule 1
ref1 is of String type which is same

String ref1 = new String();
String ref2 = (Object) ref1 ; // satisfy rule 1
ref1 is of String type which is child of Object 

String ref1 = new String();
String ref2 = (Integer) ref1; // doesn't satisfy rule 1
ref1 is of String type which is not related to Integer 
Error: incompatible types: String cannot be converted to Integer

2. Comprobar si hay una asignación válida

Después de la reducción, el tipo del objeto se escribirá como D. Sabemos que se puede hacer referencia a un objeto por el mismo tipo o por su padre. Esto lleva a la segunda regla de que el tipo de ref2, el tipo C debe ser un padre o el mismo que el tipo D. Si esta regla no se cumple, el compilador arrojará un error. Teniendo en cuenta esta regla, veamos algunas afirmaciones que cumplen los criterios.

Object ref1 = new String();
Object ref2 = (String) ref1 ; // satisfy rule 1 & rule 2
downcasted object of String type is referred by parent type Object

Object ref1 = new String();
Integer ref2 = (Integer) ref1; // satisfy rule 1 & rule 2
downcasted object of Integer type is referred by same type

Object ref1 = new String();
String ref2 = (Object) ref1; // satisfy rule 1 but not rule 2
downcasted object of Object type is referred by child class type String
Error: incompatible types: Object cannot be converted to String

String ref1 = new String();
Integer ref2 = (Integer) ref1; // doesn't satisfy rule 1 & rule 2
downcasted object of Integer type is referred by unrelated class type String
Error: incompatible types: String cannot be converted to Integer

3. Compruebe la compatibilidad del tipo de objeto en tiempo de ejecución

Si nos fijamos en los dos puntos anteriores, cubren solo los tipos de referencia y el tipo convertido. El tipo de tiempo de ejecución real del objeto que estamos tratando de reducir aún no se tiene en cuenta. JVM ahora considerará este tipo de tiempo de ejecución para verificar su validez. El objeto de la clase secundaria se puede convertir en la misma clase o clase principal. Esto lleva a la tercera regla de tiempo de ejecución, que es que el tipo D debe ser padre o igual que el tipo de tiempo de ejecución de ref1, es decir, tipo B. Si esta condición falla, la JVM lanzará ClassCastException en tiempo de ejecución. Teniendo en cuenta esta regla, veamos algunas afirmaciones que cumplen los criterios.

Object ref1 = new String();
Object ref2 = (String) ref1 ; // satisfy rule 1, rul2  & rule 3
downcasted object of String type is same as runtime type String

Object ref1 = new Integer();
Object ref2 = (Number) ref1 ; // satisfy rule 1, rul2  & rule 3
downcasted object of Number type is same parent of runtime type Integer

Object ref1 = new String();
Integer ref2 = (Integer) ref1; // satisfy rule 1, rule 2 but not rule 3
downcasted object of Integer type is not same or parent of runtime type String
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer

Publicación traducida automáticamente

Artículo escrito por jainlovely450 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *