Parent class: Public classParent { PublicString name; PrivateString Pass; Public voidsay1 (aa aa) {System.out.println ("Parent Say1"); } @SuppressWarnings ("Unused") Private voideat () {System.out.println ("Parent Eat"); } PublicString Getpass () {returnPass; } Public voidSetPass (String pass) { This. pass =Pass; }} Subclass: Public classChildextendsparent{ Public Static voidMain (string[] args) {AA a=NewAA (); /*** Upward Transformation: When a program runs a call to a method, first see if the parent class has a calling method, * if any, call the method in the subclass, and if the parent class does not have this method, compile the error. * */Parent P=NewChild (); P.say1 (a); /*** down transformation, compile and run without error, here the downward transformation is safe. */ Child Child=(child) p; Child.say1 (a); Child.say2 (a); /*** Downward transformation, compile error-free, run times wrong: java.lang.ClassCastException * unsafe downward transformation. */ //parent P2 = new parent (); //Child C2 = (child) P2; //C2.say1 (a); } Public voidsay1 (aa aa) {System.out.println ("Child Say1"); } Public voidsay2 (aa aa) {System.out.println ("Child Say2"); }}classAA { Public voidsys () {System.out.println ("A is"); }}classBbextendsaa{ Public voidsys () {System.out.println ("B is"); }}
Java Polymorphism (i)