0

Understanding Upcasting and Downcasting

Hello! I would like to start of with I am a beginner in Java and I am having trouble understanding how Class related casting works. Using the example from the Up/Down-casting module, I do not understand where the casting is implemented and how it changes what 'could be' the initial script. I have added comments on what I understand and what i need clarification on, thanks in advance! // What is the output of this code? class A { public void print() { // System.out.println("A"); } } class B extends A { //cast B onto A method which is print() public void print() { //print() prints Letter B when B is upcast onto A? needs help System.out.println("B"); } public static void main(String[ ] args) { A object = new B(); //how does the first 'B' affect the code here? //what would make this code print A instead of B? B b = (B) object; b.print(); } }

3rd May 2018, 11:33 PM
Jahlen Parker
Jahlen Parker - avatar
1 Respuesta