For the below code:
Why is it that this fails:public interface Printable { void print(); } class ShoppingItem { public void description() { System.out.println("Shopping Item"); } } class Book extends ShoppingItem implements Printable { public void description() { System.out.println("Book"); } public void print() { System.out.println("Printing book"); } } }
And this succeeds?:class MyClass { public static void main(String args[]) { Printable printable = new Book();//Implicit cast printable.description(); //This fails }
class MyClass { public static void main(String args[]) { Printable printable = new Book();//Implicit cast ((Book)printable).description(); //Explicit cast - This works }
I had initially understood that the reference could only access members of the object that it shared. Implicit casting is what makes this possible by cause I can assign a sub-class to a superclass reference .
Explicit casting (in this example that I'm reading) seems to indicate that explicit casting gives a base-class reference type access to the finer implementation of the subclassed object.
Is this correct? It seems that implicit and explicit casting are complimentary and don't overlap at all.