Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a class encapsulating the concept of a Home, assuming that it has the foll

ID: 3582954 • Letter: W

Question

Write a class encapsulating the concept of a Home, assuming that it has the following attributes: the number of rooms, the square footage, and whether it has a basement. Write a client program that creates five home objects, writes them to a file as objects, then reads them from a file as objects, outputs a description of the object using the toString() method (which the Home class should override), and outputs the number of Home objects. When reading the objects, you should assume that you do not know the number of objects in the file.

Explanation / Answer

import java.io.*;
class Home implements java.io.Serializable
{
   int num_rooms;
   float area;
   boolean basement;

   Home(int n, float f, boolean b)
   {
      num_rooms=n;
      area=f;
      basement=b;
   }

   public String toString()
   {
      String b="No";
      if(basement) b="Yes";
      return " Rooms: "+num_rooms+" Area: "+area+" Basement: "+b+" ";
   }
}

public class SerializableDemo
{
   public static void main(String a[]) throws Exception
   {
      Home h1, h2, h3,h4,h5;
       h1=new Home(4,200,false);
       h2=new Home(7,1200,true);
       h3=new Home(4,250,false);
       h4=new Home(5,500,true);
       h5=new Home(4,150,false);
     
       FileOutputStream fileOut=null;
       ObjectOutputStream out=null;
     
       FileInputStream fileIn=null;
       ObjectInputStream in=null;
     
       try
       {
         fileOut = new FileOutputStream("Home.ser");
         out = new ObjectOutputStream(fileOut);
         out.writeObject(h1);
         out.writeObject(h2);
         out.writeObject(h3);
         out.writeObject(h4);
         out.writeObject(h5);
         out.close();
         fileOut.close();
         System.out.println("Room details saved in Home.ser");
       
       
       
        /////////////////////////////////////
         System.out.println("Reading Room details from Home.ser");
         fileIn = new FileInputStream("Home.ser");
         in = new ObjectInputStream(fileIn);
         Home h;
         while((h = (Home) in.readObject())!=null)
         {
          
            System.out.println(h);
         }
       }
      catch(IOException i) {
        // i.printStackTrace();
      }
       catch(ClassNotFoundException i) {
         i.printStackTrace();
      }
      finally {
        if(fileIn!=null)fileIn.close();
        if(in!=null)in.close();
       
    }
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote