Startertutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Java » Programs » Inheritance » Java program on rodent hierarchy
Suryateja Pericherla Categories: Inheritance. No Comments on Java program on rodent hierarchy
0
(0)

In this article we will learn to implement a Java program on rodent hierarchy. A Java program is provided below which uses the rodent hierarchy to demonstrate inheritance in Java.

 

Java program to create an inheritance hierarchy of Rodent, Mouse, Gerbil, Hamster etc. In the base class provide methods that are common to all Rodents and override these in the derived classes to perform different behaviors, depending on the specific type of Rodent. Create an array of Rodent, fill it with different specific types of Rodents and call your base class methods.

 

Program is as follows:

class Rodent
{
	void eat()
	{
		System.out.println("Rodent is eating");
	}
	void run()
	{
		System.out.println("Rodent is running");
	}
}
class Mouse extends Rodent
{
	void eat()
	{
		System.out.println("Mouse is eating");
	}
	void run()
	{
		System.out.println("Mouse is running");
	}
}
class Gerbil extends Rodent
{
	void eat()
	{
		System.out.println("Gerbil is eating");
	}
	void run()
	{
		System.out.println("Gerbil is running");
	}
}
class Hamster extends Rodent
{
	void eat()
	{
		System.out.println("Hamster is eating");
	}
	void run()
	{
		System.out.println("Hamster is running");
	}
}
class RodentsDemo
{
	public static void main(String args[])
	{
		Rodent r[] = new Rodent[3];
		r[0] = new Mouse();
		r[1] = new Gerbil();
		r[2] = new Hamster();

		r[0].eat();
		r[0].run();

		r[1].eat();
		r[1].run();

		r[2].eat();
		r[2].run();
	}
}

 

Output for the above program is as follows:

Mouse is eating
Mouse is running
Gerbil is eating
Gerbil is running
Hamster is eating
Hamster is running

 


Subscribe to our monthly newsletter. Get notified about latest articles, offers and contests.


How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory