RULE-3 The Underlying original object type of d must be either same or derived type of C. If this condition is not satisfied it gives us Runtime error
Class Animal{}
Class Petanimal Extends Animal{}
Class Wildanimal Extends Animal{}
Class Cat Extends Petanimal{}
Class Dog Extends Petanimal{}
Class Lion Extends Wildanimal{}
Class Tiger Extends Wildanimal{}
public class ClassCastException{
public static void main(String[] args){
}
}
Wildanimal a = new Tiger(); ValidTiger u = new (Tiger) a; ValidPetanimal v = (Petanimal)a; CompileTime ErrorWildanimal w = (Wildanimal)a; ValidAnimal x = (Lion)a RunTime ErrorWildanimal y = (Petanimal)a CompileTime ErrorIdtRoundingDto idtRoundingDto = (IdtRoundingDto) mappedGeneralResponse InvalidIdtRoundingDto idtRoundingDto = (IdtRoundingDto) payloadableList valid@Data @AllArgsConstructor @NoArgsConstructor @ToString
public class IdtRoundingDto implements Paylodable{
private List<IdtRounding> patients;
public interface Payloadable
@Data @AllArgsConstructor @NoArgsConstructor @ToString
public class MappedGeneralResponse implements Paylodable{
private List<Payloadable> data;
public Payloadable getReport(map<String, Object> request){
MappedGeneralResponse mappedGeneralResponse = service.getDataFromDb(new IdtRoundingDto());
}
public MappedGeneralResponse getDataFromDb(Payloadable reportData){
}
IdtRoundingDto idtRoundingDto = mappedGeneralResponse.getData.get(0);
Its shows an compiletime error βCast to IdtRoundingDtoβ since mappedGeneralResponse is of type Payloadable type which cannot be assigned to idtRoundingDto which is of IdtRoundingDto type. Required type is IdtRoundingDto but we provided payloadable.
IdtRoundingDto idtRoundingDto = (IdtRoundingDto) mappedGeneralResponse.getData.get(0);
compile error will be fixed but it gives us runtime error because mappedGeneralResponse is not either same or derived type of IdtRoundingDto Which fails rule 3 of object typeCasting.
public Payloadable getReport(map<String, Object> request){
IdtRoundingDto idtRoundingDto = convertToIdtRoundingDto(mappedGeneralResponse);
return idtRoundingDto;
}
private IdtRoundingDto convertToIdtRoundingDto(MappedGeneralResponse mappedGeneralResponse){
List<Payloadable> payloadableList = mappedGeneralResponse.getData();
IdtRoundingDto idtRoundingDto = (IdtRoundingDto) payloadableList.get(0);
return idtRoundingDto;
}