JAVA object oriented - Polymorphism

The so-called polymorphism, refers to a reference (type) a plurality of states under different conditions. You can also be understood, it refers to polymorphic parent class pointer to invoke the method implemented in different sub-classes.

 

Precautions

Ⅰ.java allows the parent class reference variable reference instance (object) of its subclasses, such conversion is done automatically.

Ⅱ...........

 

Examples

 1 package com.beekc.www;
 2 
 3 public class Beekc {
 4     public static void main(String[] args) {
 5         Master master = new Master();
 6         master.food(new Dog(),new Bone());
 7         master.food(new Cat(),new Fish());
 8     }
 9 }
10 
11 //主人
12 class Master
13 {
14     public void food(Animal an, Food f)
15     {
16         an.cry();
17         f.showName();
18     }
19 }
20 
21 //食物
22 class Food
23 {
24     public String Name;
25     public void showName()
26     {
27 
28     }
29 }
30 
31 class Fish extends Food
32 {
33     public void showName()
34     {
 35          System.out.println ( "love fish" );
 36      }
 37 [  }
 38 is  
39  class Bone the extends Food
 40  {
 41 is      public  void showname ()
 42 is      {
 43 is          System.out.println ( "love bones" );
 44      }
 45  }
 46 is  
47  // animal 
48  class animal
 49  {
 50      Private  int Age;
 51 is      Private String name;
 52 is      public void Cry ()
 53 is      {
 54 is          System.out.println ( "I am the animals, the system does not know how to call!" );
 55      }
 56 is  }
 57 is  
58  class Cat the extends Animal
 59  {
 60      public  void Cry ()
 61 is      {
 62 is          the System. out.println ( "cat, Mew ~" );
 63 is      }
 64  }
 65  
66  class Dog the extends Animal
 67  {
 68      public  void Cry ()
 69      {
70          System.out.println ( "dog barking ~" );
 71      }
 72 }

 

operation result

 

Guess you like

Origin www.cnblogs.com/beekc/p/12329559.html