You are here: Home / Topics / Program to Serialize object of Box class in Java

Program to Serialize object of Box class in Java

Filed under: Java on 2024-03-01 06:45:40

// Program to Serialize object of Box class.

import java.io.*;
import java.util.*;

// Box class
class  Box  implements Serializable
{
// instance variables
private double width;
private double height;
private double depth;

// default constructor
Box()
{
 width = 0;
 height = 0;
 depth = 0;
}

// parameterized constructor
Box( double w, double h, double d )
{
 width = w;
 height = h;
 depth = d;
}

// display box
void display()
{
 System.out.println(" Width = " + width);
 System.out.println(" Heidth = " + height);
 System.out.println(" Depth = " + depth);
}
}

class  SerializationDemo
{
public static void main( String args[ ] ) throws IOException
{
 // to read data from keyboard
 BufferedReader br = new BufferedReader( new InputStreamReader( System.in ));
 
 double w = 0.0, h = 0.0, d = 0;
 System.out.print("Enter width, height & depth : ");
 w = Double.parseDouble( br.readLine() );
 h = Double.parseDouble( br.readLine() );
 d = Double.parseDouble( br.readLine() );
 
 Box b1 = new Box(w, h, d);
 
 // attach FileOutputStream to file.
 FileOutputStream fos = new FileOutputStream( "ObjFile" );
 
 // attach ObjectOutputStream to FileOutputStream.
 ObjectOutputStream oos = new ObjectOutputStream( fos );
 
 // write object (b1) to 'oos'
 oos.writeObject( b1 );
 
 oos.close();
}
}


Output:

Enter width, height & depth : 
10
10
10

About Author:
G
Geetam     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.