Insects + persistence Java Exercise - Java Programming Course

 Exercise

Insects + persistence

 Objetive

Create a new version of the "insects" exercise, which should persist the data using some form of storage such as a database or file system.

 Example Code

package Insects;

public class Ant extends NonFlyingInsect
{
	@Override
	public void ShowData()
	{
		System.out.println("I am an ant.");
	}
}

package Insects;
public class Bee extends FlyingInsect
{
	@Override
	public void ShowData()
	{
		System.out.println("I am a bee.");
	}
}

package Insects;

public class Fly extends FlyingInsect
{
	@Override
	public void ShowData()
	{
		System.out.println("I am a fly.");
	}
}

package Insects;

public class FlyingInsect extends Insect
{
	@Override
	public void ShowData()
	{
		System.out.println("I am a flying insect.");
	}
}

package Insects;
public class Insect implements Serializable
{
	public void ShowData()
	{
		System.out.println("I am an insect.");
	}

	public static void Guardar(String nombre, Insect insect)
	{
		IFormatter formatter = new BinaryFormatter();
		Stream stream = new java.io.FileOutputStream(nombre);
		formatter.Serialize(stream, insect);
		stream.Close();
	}

	public static Insect Cargar(String nombre)
	{
		Insect objeto;
		IFormatter formatter = new BinaryFormatter();
		Stream stream = new java.io.FileInputStream(nombre);
		objeto = (Insect)formatter.Deserialize(stream);
		stream.Close();
		return objeto;
	}
}

package Insects;
public class Mosquito extends FlyingInsect
{
	@Override
	public void ShowData()
	{
		System.out.println("I am a mosquito.");
	}
}

package Insects;
public class NonFlyingInsect extends Insect
{
	@Override
	public void ShowData()
	{
		System.out.println("I am a non flying insect.");
	}
}

package Insects;
import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
		Random rand = new Random();
		int amount = 10;
		Insect[] data = new Insect[amount];
		for (int i = 0; i < amount - 1; i++)
		{
			switch (rand.nextInt(1, 5))
			{
				case 1:
					data[i] = new Fly();
					break;
				case 2:
					data[i] = new Mosquito();
					break;
				case 3:
					data[i] = new Bee();
					break;
				case 4:
					data[i] = new Ant();
					break;
				case 5:
					data[i] = new Spider();
					break;
			}
		}

		for (int i = 0; i < amount - 1; i++)
		{
			data[i].ShowData();
		}

	}
}

package Insects;
public class Spider extends NonFlyingInsect
{
	@Override
	public void ShowData()
	{
		System.out.println("I am a spider.");
	}
}


Juan A. Ripoll - Programming Tutorials and Courses © 2024 All rights reserved.  Legal Conditions.