Answer the question
In order to leave comments, you need to log in
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
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question