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.

Categories: Inheritance. No Comments on Java program on rodent hierarchy

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

 

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?

Suryateja Pericherla

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.

He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.

He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.

Leave a Reply

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