// INHERIT0_DETAILED // more about assigning objects of different types // discussed more during polymorphism /* Purpose: * Imagine that $double$ is `wide' and $int$ is `thin'. * Based on numbers and type, an integer is (or, can be) a double. * So, doubles resemble superclasses of integers. * Can also say, doubles as `wider' than integers. */ class wide {} // `double' (class A) class thin extends wide {} // `int' (class B) public class inherit0_detailed { public static void main(String[] args) { /***************************************************************************************************/ /* Assignment Types Type Var Value Output */ /***************************************************************************************************/ /* wide gets wide: primitive */ double y1 = 1.2; System.out.println(y1); /* wide gets wide: object */ wide x1 = new wide(); System.out.println(x1.getClass()); /* wide gets thin: primitive */ double y2 = 1; System.out.println(y2); /* wide gets thin: object */ wide x2 = new thin(); System.out.println(x2.getClass()); /* wide gets thin: primitive */ double y3 = (double) 1; System.out.println(y3); /* wide gets thin: object */ wide x3 = (wide) new thin(); System.out.println(x3.getClass()); /* thin gets thin: primitive */ int y4 = 1; System.out.println(y4); /* thin gets thin: object */ thin x4 = new thin(); System.out.println(x4.getClass()); /* thin gets wide: primitive */ int y5 = (int) 7.7; System.out.println(y5); /* thin gets wide: object */ thin x5 = (thin) new wide(); System.out.println(x5.getClass()); // Note: the x3 and y3 assignments are redundant versions of x2 and y2, respectively. // Another trick to remembering: // If Y is an X, then $X var = new Y()$ is OK. // Also, Y is a Y, so $Y var = new Y()$ is OK. } } /* output: 1.2 class wide 1.0 class thin 1.0 class thin 1 class thin 7 Exception in thread "main" java.lang.ClassCastException: wide at itest.main(itest.java, Compiled Code) ^^^ Why an Exception? Java has trouble reversing is-a relationships because the superclass might not contain vars/meths written in the subclass. */