*Code in Java*
Write a Java program called to demonstrate Inheritance and Polymorphism
import java.util.*;
class Person
{
private String name;
private int age;
// constructor
Person()
{
this.name = "";
this.age = 0;
}
// constructor
Person(String name, int age)
{
this.name = name;
this.age = age;
}
// setter method
public void setName(String name)
{
this.name = name;
}
public void setAge(int age)
{
this.age = age;
}
// getter method
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
// to make the person say their name (using System.out.println)
public void speak()
{
System.out.println("My name is " + this.getName());
}
}
class Dog extends Person
{
private String type;
private String voice;
Dog()
{
// call the constructor of parent class
super();
this.type = "Dog";
this.voice = "";
}
Dog(String name, int age, String voice)
{
// call the constructor of parent class
super(name, age);
this.type = "Dog";
this.voice = voice;
}
// setter method
public void setVoice(String voice)
{
this.voice = voice;
}
// getter method
public String getVoice()
{
return this.voice;
}
}
class Cat extends Person
{
private String type;
private String voice;
Cat()
{
// call the constructor of parent class
super();
this.type = "Cat";
this.voice = "";
}
Cat(String name, int age, String voice)
{
// call the constructor of parent class
super(name, age);
this.type = "Cat";
this.voice = voice;
}
// setter method
public void setVoice(String voice)
{
this.voice = voice;
}
// getter method
public String getVoice()
{
return this.voice;
}
}
public class Test
{
public static void main(String[] args)
{
ArrayList<Person> arr = new ArrayList<Person>();
arr.add( new Person("Chandler Bing", 35) );
arr.add( new Dog("Rocky", 11, "Woof") );
arr.add( new Cat("Tinker", 12, "Meow") );
// traverse the ArrayList
for( Person ob : arr )
ob.speak();
}
}
Sample Output

*Code in Java* Write a Java program called to demonstrate Inheritance and Polymorphism Create a base...