/** * File: ConversionI.java * Author: Ying Li * Date: 09/29/2019 */ public class ConversionI { public static void main (String[] argv) { short i = 3; int j = 2147483647; // Java will do implicit conversion for the operation, but not the assignment short s = (short) (i + j); System.out.println("short " + i + " int j " + j + " short s " + s); int n = i + j; System.out.println("short " + i + " int j " + j + " int n " + n); int a = 1; Integer b = 2; int c = a + b; // b is unboxed before being added to a. Integer d = a + b; // b is unboxed, then the sum is boxed. System.out.println( a ); System.out.println( b ); System.out.println( c ); System.out.println( d ); Parent p1 = new Parent(100); System.out.println("p1 is " + p1); System.out.println("p1 is happy " + p1.isHappy()); Child c1 = new Child(101); System.out.println("c1 is " + c1); System.out.println("c1 is happy " + c1.isHappy()); System.out.println( "c1 has age " + c1.age()); Parent p2 = new Child(102); System.out.println("p2 is " + p2); System.out.println("p2 is happy " + p2.isHappy()); // dynamic dispatching!!! It will call the "right" method - Child... // System.out.println( "p2 has age " + p2.age()); // can't do this!!! Child c3 = (Child) p2; // downcast System.out.println("c3 is " + c3); System.out.println("c3 is happy " + c3.isHappy()); System.out.println( "c3 has age " + c3.age()); // works now! // Child c2 = (Child) p1; // compiles, but causes a runtime error // System.out.println("c2 is " + c2); // System.out.println("c2 is happy " + c2.isHappy()); // // Casting (explicit conversion) doesn't change the bits of the reference, it just changes // what operations appear available to the compiler Parent p3 = (Parent) c1; // this cast does not change the methods actually available to the object. Child c4 = (Child) p3; // because we can cast back. System.out.println( "c4 has age " + c4.age()); // works now! // } } class Parent { protected long id; public Parent (long id) { this.id = id; } public String toString () { return Long.toString(id); } public boolean isHappy () { return false; } } class Child extends Parent { public Child (Integer id) { super(id); } public boolean isHappy () { return true; } public int age() { return 2; } }