Java Novice Note 15 polymorphic

Source: Internet
Author: User

1.Animal class

Package Com.yfs.javase;public class Animal {public void Cry () {System.out.println ("animal called ...");}}

2.dog/cat/bird class

Package Com.yfs.javase;public class Dog extends Animal {public void Cry () {System.out.println ("barking ...");} Class Cat extends Animal {public void Cry () {System.out.println ("Meow meow ...");}} Class Bird extends Animal {public void Cry () {System.out.println ("quack ...");}}

3.Box class, (collection)

Package Com.yfs.javase;public class Box {//animal room where 10 animals//private dog[] dogs = new Dog[10];//private cat[] cats = new cat[ 10];//private bird[] birds = new bird[10];//Declare parent class array private animal[] animals = new ANIMAL[10];p rivate int index = 0;//loaded animal PU Blic void Addanimal (Animal pet) {if (index >=) {System.out.println ("box full"); return;} Animals[index] = pet;index++;//system.out.println (PET);} public void Addanimal (cat cat) {//if (index >=) {//system.out.println ("case is full");//return;//}//cats[index] = Cat ;//index++;//}//kick Box public void Kid () {for (int i = 0; i < animals.length; i++) {animals[i].cry ();//The method that performs the subclass is polymorphic  overwrite Method}}}

4.Box Test

Package Com.yfs.javase;import Java.util.random;public class Boxtest {public static void main (string[] args) {Box box = new Box ();//box.addanimal (new Dog ());//box.addanimal (new Bird ());//box.addanimal (new Cat ());  Random ran = new random (), for (int i = 0; i < i++) {int r = ran.nextint (101);//(  r > ) {Box.addanimal (New Dog ()),} else if (R >) {box.addanimal (New Cat ());} else {box.addanimal (new Bird ());}} Box.kid ();}}

Java Novice Note 15 polymorphic

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.