Upward transformation: Father F=new Child ();
Downward transformation:
Father F=new Child 2 ();
Child 2 c= (Child 2) f;//child c=f; This is wrong, assigning a parent object directly to a subclass is an error because the parent class object is not necessarily an instance of the subclass.
A quadrilateral is not necessarily parallelogram may be trapezoidal, the more specific objects have more characteristics, the more abstract objects have fewer features, in the downward transition operation, the feature range of small objects into a large range of objects will certainly be a problem, so you need to tell the compiler this object is parallelogram.
Casting a parent class object to a child class object is called an explicit type conversion. Must be used when transitioning down.
1 classperson{2 PrivateString name;3 Private intMoney ;4 PublicPerson () {5Name= "Tom";6money=1000;7 }8 PublicPerson (String Name,intMoney ) {9Name=Name;Tenmoney=Money ; One } A Public voidFeed (Pet pet) { - pet.eat (); - if(PetinstanceofDog) { themoney-=10; -}Else if(PetinstanceofPenguin) { -Money-=20; - } +System.out.println ("The master ' s remanent money is" +Money ); - } + } A classpet{ at protectedString name; - protected intHealth ; - PublicPet () { -Name= "PP"; -health=100; - } in Public voideat () { -System.out.println ("Pet Eat"); to } + } - classDogextendspet{ the Public voideat () { *health+=10; $System.out.println ("Dog Eat");Panax Notoginseng } - } the classPenguinextendspet{ + Public voideat () { AHealth+=20; theSystem.out.println ("Penguin eat"); + } - } $ Public classhelloworld{ $ Public Static voidMain (String args[]) { -Person liming=NewPerson ("Liming", 2000); -Dog d=NewDog (); thePenguin p=NewPenguin (); - Liming.feed (d);Wuyi liming.feed (p); the } -}
The example of this man feeding an animal can also explain
The result is
A good example of learning upward transformation and downward transformation