참조 유형 변환 - 1

"그리고 이제 Diego의 짧은 교훈입니다. 간략하고 요점입니다. 참조 유형 변환에 대해."

"개체 변수부터 시작하겠습니다. 이러한 변수에 모든 참조 유형을 할당할 수 있습니다( 확대 변환 ). 그러나 다른 방향으로 할당( 축소 변환 )하려면 캐스트 작업을 명시적으로 지정해야 합니다."

암호 설명
String s = "mom";
Object o = s; // o stores a String
일반적인 확장 참조 변환
Object o = "mom"; // o stores a String
String s2 = (String) o;
일반적인 축소 참조 변환
Integer i = 123; // o stores an Integer
Object o = i;
확대 변환.
Object o = 123; // o stores an Integer
String s2 = (String) o;
런타임 에러!
정수 참조를 문자열 참조로 캐스팅할 수 없습니다.
Object o = 123; // o stores an Integer
Float s2 = (Float) o;
런타임 에러!
Integer 참조를 Float 참조로 캐스팅할 수 없습니다.
Object o = 123f; // o stores a Float
Float s2 = (Float) o;
동일한 유형으로 변환. 축소 참조 변환입니다.

" 넓히거나 좁히는 참조 변환은 어떤 식으로든 개체를 변경하지 않습니다. 좁히기(또는 넓히기) 부분은 특히 할당 작업에 변수 및 해당 새 값의 유형 검사가 포함(포함되지 않음)한다는 사실을 나타냅니다. "

"이것은 모든 것이 명확한 드문 예입니다."

" 이러한 예제의 오류를 방지하기 위해 Object 변수가 참조하는 유형을 찾을 수 있는 방법이 있습니다 .  "

암호
int i = 5;
float f = 444.23f;
String s = "17";
Object o = f;                       // o stores a Float

if (o instanceof  Integer)
{
    Integer i2 = (Integer) o;
}
else if (o instanceof  Float)
{
    Float f2 = (Float) o;            // This if block will be executed
}
else if (o instanceof  String)
{
    String s2 = (String) o;
}
3
과제
Java Syntax,  레벨 10레슨 6
잠금
Code entry
Your attention, please! Now recruiting code entry personnel for CodeGym. So turn up your focus, let your fingers relax, read the code, and then... type it into the appropriate box. Code entry is far from a useless exercise, though it might seem so at first glance: it allows a beginner to get used to and remember syntax (modern IDEs seldom make this possible).

"객체의 유형을 100% 확신하지 않는 한 모든 확대 변환 전에 이 검사를 수행해야 합니다."

"알았어요."