Q:

java programming polymorphism simple example | Animals program

belongs to collection: Java Inheritance Programs

0

this a polymorphism example in java

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Animal class:

class Animal
{
	protected String name;
	protected int age;
	public Animal()
	{
		this("", 0);
	}
	public Animal(String name, int age)
	{
		this.name = name;
		this.age = age;
	}
	public String toString()
	{
		String s = "Name="+name+", age="+age;
		return s;
	}
	public void Speak()
	{
		System.out.println("Animal speaking...");
	}
}

Fish class:

class Fish extends Animal
{
	private int swimmingSpeed;
	public Fish()
	{
		super("", 0);
		swimmingSpeed=0;				
	}
	public Fish(String name, int age, int sp)
	{
		super(name, age);
		swimmingSpeed=sp;				
	}
	public String toString()
	{
		String s = "Name="+name+", age="+age+", SwimSpeed="+swimmingSpeed+" km/hr";
		return s;
	}
}

 

Cat class:

class Cat extends Animal
{
	private int runningSpeed;
	public Cat()
	{
		super("", 0);
		runningSpeed=0;				
	}
	public Cat(String name, int age, int sp)
	{
		super(name, age);
		runningSpeed=sp;				
	}
	public String toString()
	{
		String s = "Name="+name+", age="+age+", runningSpeed="+runningSpeed+" km/hr";
		return s;
	}
	public void Speak()
	{
		System.out.println("meow....");
	}
	
}

 

Test class:

public class Test
{
	public static void main(String[] args)
	{
		Animal a = new Animal("Tiger", 5);
		Fish f = new Fish("Whale", 40, 60);
		Cat c = new Cat("Tom", 3, 10);
		System.out.println(a);
		System.out.println(f);
		System.out.println(c);
		a.Speak();
		f.Speak();
		c.Speak();
		
	}
}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

<< Java program to demonstrate the protected access s...