A
A
Alexey24112020-08-06 20:24:34
Java
Alexey2411, 2020-08-06 20:24:34

How does downcast work in Java?

I didn't fully understand how downcasting works in Java. Can you explain in detail why there is no loss of information when we first perform upstream and then downstream transformations?

class Mother {
    private final String MothersName;
    public Mother(String MothersName) { this.MothersName = MothersName; }
    public String getMothersName() { return MothersName; }
}

class Child extends Mother {
    private final String name;
    public Child(String name, String mothersName) {
        super(mothersName);
        this.name = name;
    }
    public String getName() { return name; }
}

public class Main {
    public static void main(String[] args) {

        Mother mother = new Child("John", "Amanda");
        Object obj = mother; // Восходящее преобразование, все работает как надо

        /*
        Нисходящее преобразование.
        По моей логике ( видимо ошибочной ), должна быть потеря информации.
         */
        Mother newMother = (Mother) obj;
        Child newChild = (Child) obj;

        System.out.println(newMother.getMothersName()); // Output: Amanda
        System.out.println(newChild.getName()); // Output: John
    }
}


Does this mean that at run time the type "obj" is treated as the type of the object assigned to it, which is lower in the hierarchy, and only the compiler treats it as Object?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
koperagen, 2020-08-06
@Aleksey2411

During conversions, only the type of the reference that refers to the object in memory changes. He himself remains forever the same type as when he was created.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question