OK, noob question. I'm studying for the SCJP and got 3 questions on object reference casting wrong which all seem to point to the same misunderstanding. Just wanted to confirm what the right insight should be. Right, here are the questions:
-
1.
1. class CodeWalkFour { 2. public static void main(String[] args){ 3. Car c = new Lexus(); 4. System.out.print(c.speedUp(30) + " "); 5. Lexus l = new Lexus(); 6. System.out.print(l.speedUp(30, 40, 50)); 7. } 8. } 9. class Car { 10. private int i=0; 11. int speedUp(int x){ 12. return i; 13. } 14. } 15. class Lexus extends Car { 16. private int j = 1; 17. private int k = 2; 18. int speedUp(int y){ 19. return j; 20. } 21. int speedUp(int... z){ 22. return k; 23. } 24. }
I thought that after line 3, c would be a Car, not a Lexus, so the Car.speedUp method would be called, not the Lexus.speedUp method. Turns out it's the latter that's called.
-
2.
1. class StudentProb { 2. private int studentId = 0; 3. void setStudentID(int sid) { 4. student_id = sid; 5. System.out.println("Student ID has been set to " + sid); 6. } 7. public static void main(String args[]) { 8. int i = 420; 9. Object ob1; 10. StudentProb st1 = new StudentProb(); 11. ob1 = st1; 12. st1.setStudentID(i); 13. } 14. }
Same problem. I thought line 11 would make st1 an Object, not a StudentProb anymore. How does the compiler still know where to find setStudentID?
-
3.
1. LectureHall lh = new LectureHall(); 2. Auditorium a1; 3. Facilities f1; 4. 5. f1 = lh; 6. a1 = f1;
Facilities is an interface. The class ClassRoom implements Facilities, and Auditorium and LectureHall are subclasses of ClassRoom. Same question: I thought after line 5, both f1 and lh would be LectureHall. But f1 is still Facilities. So what exactly does casting do here?
Thanks all!
PS: code formatting doesn't work for me somehow. Feel free to edit.