1 //The connection and difference between inheritance and composition in Java2 //This example is inherited3 4 classAnimal5 {6 Private voidBeat ()7 {8System.out.println ("Beating heart ...");9 }Ten Public voidBreath () One { A beat (); -System.out.println ("Inhale, breath, breathe ..."); - } the } - //inherit animal, directly reuse the breath () method of the parent class - classBirdextendsAnimal - { + Public voidFly () - { +System.out.println ("I fly freely in the sky ..."); A } at } - //inherit animal, direct reuse parent class breath () method - classWolfextendsAnimal - { - Public voidRun () - { inSystem.out.println ("I'm running fast on land ..."); - } to } + Public classinherittest - { the Public Static voidMain (string[] args) * { $Bird B =NewBird ();Panax Notoginseng B.breath (); - b.fly (); theWolf W =NewWolf (); + W.breath (); A W.run (); the } +}
1 //The connection and difference between inheritance and composition in Java2 //This example is a combination3 classAnimal4 {5 Private voidBeat ()6 {7System.out.println ("Beating heart ...");8 }9 Public voidBreath ()Ten { One beat (); ASystem.out.println ("Inhale, breath, breathe ..."); - } - } the classBird - { - //Combines the original parent class into a subclass as a combined part of the subclass. - PrivateAnimal A; + PublicBird (Animal a) - { + This. A =A; A } at //redefine one's own breath () method - Public voidBreath () - { - //Direct multiplexing of the breath () method provided by the animal to implement the bird Breath () method - A.breath (); - } in Public voidFly () - { toSystem.out.println ("I'm flying in the sky ..."); + } - } the classWolf * { $ //Combines the original parent class into a subclass as a combined part of the subclass.Panax Notoginseng PrivateAnimal A; - PublicWolf (Animal a) the { + This. A =A; A } the //redefine one's own breath () method + Public voidBreath () - { $ //Direct multiplexing of the breath () method provided by the animal to implement the bird Breath () method $ A.breath (); - } - Public voidRun () the { -System.out.println ("I'm running fast on land ...");Wuyi } the } - Wu Public classcompositetest - { About Public Static voidMain (string[] args) $ { - //you need to display the object that you created the group at -Animal A =NewAnimal (); -Bird B =NewBird (a); A B.breath (); + b.fly (); the - //you need to display the object that you created the group at $Animal A2 =NewAnimal (); theWolf W =NewWolf (A2); the W.breath (); the W.run (); the } -}
Relationships and differences between inheritance and composition in <java >