Task 1: Polymorphism
public class Animal
{
Animal (){}
public void animalSound()
{
System.out.println("Animals
make different sounds");
}
}
public class Cow extends Animal{
Cow(){}
public void animalSound()
{
System.out.println("The
cow says: moo moo");
}
}
public class Test
{
public static void main(String[] args)
{
Animal animal = new Animal();
Cow cow = new Cow();
animal.animalSound();
cow.animalSound();
}
}
public class Dog extends Animal
{
Dog(){}
public void animalSound()
{
System.out.println("The
dog says: bow wow");
}
//overloading the AnimaSound
method
public void animalSound(String angry)
{
System.out.println("The
angry dog says: growl growl");
//super.animalSound();//try
it
}
}
public class Test
{
public static void main(String[] args)
{
Animal animal = new Animal();
Cow cow = new Cow();
Dog dog = new Dog();
Animal cow2 = new Cow();//polymorphism
Animal dog2 = new Dog();//polymorphism
animal.animalSound();
cow.animalSound();
dog.animalSound();
dog.animalSound("angry");//pass
any string
cow2.animalSound();
dog2.animalSound();
}
}
Task 2: The “instanceof” operator
public class Bird{
public void sing()
{
System.out.println("Singing!");
}
}
public class Eagle extends Bird{ }
public class Test
{
public static void main(String[] args)
{
Bird e1 = new Eagle();
Eagle e2 = new Eagle();
Bird b1 = new Bird();
System.out.println(e1 instanceof Bird);
System.out.println(e2 instanceof Bird);
System.out.println(e2 instanceof Eagle);
if (b1 instanceof Eagle )
{
Eagle e3 =
(Eagle) b1;
System.out.print(e3);
} else {System.out.println("TypeCasting
cant be done");}
}
}
Task 1: Polymorphism public class Animal { Animal (){} public void animalSound() { System.out.println("Animals make diff
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
Task 1: Polymorphism public class Animal { Animal (){} public void animalSound() { System.out.println("Animals make diff
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!