Pages

2013-05-06

[Java]Polymorphism (多型)


In Java programming, subclass can override the methods in superclass via  Inherit. Thus, there is a method implemented by many different functions in different classes.But what is Polymorphism?

For example, we have classes "Animal", "Dog", "Cat" and "Bird" and the above classes "Dog", "Cat" and "Bird" inherit class "Animal". Among these classes, there are different attributes themselves. In addition, there are also the smae method in some classes. When we new instance of object "Dog", "Cat" or "Bird", we can force it to change the type to superclass "Animal" and access the method in class which we want to use.


code : 
import java.lang.Math;

class Animal{
 public void speak(){
  System.out.println("......");
 }
}

class Dog extends Animal{
 public void speak(){
  System.out.println("I'm a dog! 汪汪");
 }
}

class Cat extends Animal{
 public void speak(){
  System.out.println("I'm a cat! 喵喵");
 }
}

class Bird extends Animal{
 public void speak(){
  System.out.println("I'm a bird! 啾啾");
 }
}

public class Demospeak{

 public static void main(String[] args) {
  
  Animal [] arrA = new Animal[10];
  
  for (int i=0;i<arrA.length;i++){
   
   int x=(int)(Math.random()*3);
  
   switch(x){
   
   case 0:
    arrA[i] = new Dog();
    break;
   case 1:
    arrA[i] = new Cat();
    break;
   case 2:
    arrA[i] = new Bird();
    break;
   
   }
   
  }
  
  for (int j=0;j<arrA.length;j++){
   arrA[j].speak();
  }
 
 }

}
output : 
I'm a bird! 啾啾
I'm a dog! 汪汪
I'm a dog! 汪汪
I'm a cat! 喵喵
I'm a dog! 汪汪
I'm a cat! 喵喵
I'm a cat! 喵喵
I'm a bird! 啾啾
I'm a dog! 汪汪
I'm a dog! 汪汪

No comments:

Post a Comment