1.WAJP
that illustrates how runtime polymorphism is achieved.
Program:
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();
}
}
}
}
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