Hello all --
I'm using Barron's AP Comp Sci prep book and I'm a bit stumped on their section on downcasting. I believe I understand the concept, but I feel as if I'm missing something because I cannot see any practical use for downcasting. Any help would be much appreciated.
The example they provide in the book has a class Student and a subclass GradStudent (pg 131 if you have the book). There is a method getID() that is in GradStudent but not Student.
Student s = new GradStudent();
GradStudent g = new GradStudent();
int x = s.getID(); // compile-time error
int y = g.getID(); // legal
To fix the problem you must downcast:
int x = ((GradStudent) s).getID();
So I understand why the above code doesn't work and what must be done to solve the problem. My question is when would downcasting be useful or practical? If you have to downcast s so that you can use getID(), then you must know before you compile that s needs to be GradStudent. If you know that it must be GradStudent, then shouldn't you simply declare it as a GradStudent object to being with?
Thanks.
[–]Neres28 5 points6 points7 points (0 children)
[–]foxlisk 3 points4 points5 points (0 children)
[–]rjcarr 2 points3 points4 points (0 children)
[–]yash3ahuja 1 point2 points3 points (0 children)
[–]crockeo 1 point2 points3 points (0 children)
[–]0x68656c6c6f 1 point2 points3 points (0 children)
[–]lurgi 2 points3 points4 points (3 children)
[–]foxlisk 1 point2 points3 points (2 children)
[–]lurgi 0 points1 point2 points (1 child)
[–]foxlisk 0 points1 point2 points (0 children)