Well, here's the last time didn't see? Down, let the reader combine with the example of the upward transformation discussed last time (in fact, this code is also added, rest assured).
Here we want to explore the two basic situations that will arise from a downward transition.
Package downcasting;//Animal class Animal Parent classClass animal{String name;intAge PublicStringGetName() {returnName } Public void SetName(String name) { This. name = name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age = Age; }//animals will be called Public void Cry() {System. out. println ("Don't know what to call it."); }//animals eat things Public void Eat() {System. out. println ("I don't know what to eat."); }}//Create a dog subclass and extends inherit animal parent class and Overwrite cry methodClass Dog extends animal{//Dog Bark Public void Cry(){//Override parent class methodSystem. out. println ("bark."); }//dog eats something Public void Eat(){//Override parent class methodSystem. out. println ("Dogs love bones."); } Public void Bite() {System. out. println ("The dog will bite ..."); }} Public classdowncasting { Public Static void Main(string[] args) {//TODO auto-generated method stubAnimal g1=NewDog ();//Upward TransformationG1.cry (); G1.eat ();/* Case ONE: If the object referenced by the parent class refers to a sub-class object that is pointed to, the * is safe in the process of downward transformation. That is, compile and run will not be wrong * /Dog dog= (dog) G1;//down transformation, compile and run without errorDog.cry (); Dog.eat (); Animal g2=NewAnimal ();/* Case TWO: If the parent class refers to an object that is the parent class itself, it is unsafe in the process of downward transformation, * compilation does not go wrong, but java.lang.ClassCastException error occurs at run time. * It can use instanceof to avoid errors like this. * */ /* Error as follows: Exception in thread "main" java.lang.ClassCastException: * downchange. Animal cannot is cast to Downchange. Dog at Downchange. Downchange.main (downchange.java:62) Dog dog1= (dog) G2; Dog1.cry (); Dog1.eat (); */ if(G2 instanceof Dog) {Dog dog1= (dog) G2; Dog1.cry (); Dog1.eat (); }Else if(G2 instanceof Animal) {System. out. println ("G2 is an example of animal");}//dog g3=new Animal (); There is no conversion from animal to dog}}
Ps:
instanceof:
1. Use instanceof to test whether the object it points to is a class.
2.instanceof cast in the object type, first determine whether it is a certain type, yes, then cast to the modified type.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Multi-State Learning 2