Pages

Ads 468x60px

Tuesday 18 December 2012

Dynamic or runtime polymorphism



1.WAJP that illustrates how runtime polymorphism is achieved.
Program:
                                             Download link to runtime or polymorphism
      import java.util.*;
import java.lang.*;
class Animal
{
  int size,age;
 
  String colour;
 
  void eat()
  {
    System.out.println("i dont what i eat");
  }
 
  void drink()
  {
    System.out.println("I drink water");
  }
}
class Dog extends Animal
{
  String breed;
 
  void eat()
  {
    System.out.println("I like bones");
  }
 
  void drink()
  {
    System.out.println("multiple drinks accepted");
  }
}

class Tiger extends Animal
{
  String region;
 
  void eat()
  {
    System.out.println("what ever the food i hunt");
  }
 
  void drink()
  {
    System.out.println("i like human blood");
  }
}
class Horse extends Animal
{
  String region;
 
  void eat()
  {
    System.out.println("i eat grass");
  } 
 
  void drink()
  {
    System.out.println("i like water");
  }
}

class PolyTest
{
  public static void main(String[] args)
  {
    Animal[] arr =new Animal[3];
   
    int choice=(int)(Math.random()*4);
   
    for(int i=0;i<arr.length;i++)
    {
      switch(choice)
      {
        case 0: System.out.println("generated choice is"+ choice);
            
             arr[i]=new Animal();
            
             arr[i].eat();
       
        case 1: arr[i]=new Dog();
                
                 arr[i].eat();
       
        case 2: arr[i]=new Tiger();
       
             arr[i].eat();
            
        case 3: arr[i]=new Horse();
       
                arr[i].eat();
       }
     }
   }
 }                                   

0 comments:

Post a Comment

 

Sample text

Sample Text

Sample Text