Serialization with Inheritance in Java

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Program 1

import java.io.*;

class Employee implements Serializable
{
       int eid;
       String ename;
       int mobile;
      Employee(int eid,String ename,int mobile)      
      {
          this.eid=eid;
          this.ename=ename;
          this.mobile=mobile;
      }
}
class EmployeeSalary extends Employee
{
       String edept;
       int bs;
       int hra;
      EmployeeSalary(int eid,String ename,int mobile,String edept,int bs,int hra)
      {
        super(eid,ename,mobile);
        this.edept=edept;
        this.bs=bs;
        this.hra=hra;
      }
}
class TestSerial
{
    public static void main(String args[])
    {
        try
       { 
              File F=new File("c://myserial/empinfo.txt");
              FileInputStream fis=new FileInputStream(F);
              ObjectInputStream ois=new ObjectInputStream(fis);
              EmployeeSalary E1=(EmployeeSalary)ois.readObject();   
              System.out.println("Id="+E1.eid);
              System.out.println("Name="+E1.ename);
              System.out.println("Mobile="+E1.mobile);
              System.out.println("Department="+E1.edept);
              System.out.println("Basic Salary="+E1.bs);
              System.out.println("HRA="+E1.hra);
              
        //   File F=new File("c://myserial/empinfo.txt");
        //   FileOutputStream fos=new FileOutputStream(F);
        //   ObjectOutputStream oos=new ObjectOutputStream(fos);
        //   EmployeeSalary E1=new EmployeeSalary(101,"Vishal Verma",12345,"CSE",70000,8000);
        //   oos.writeObject(E1);
        //   System.out.println("File Created.............");
       }
       catch(Exception e)   
       {
         System.out.println(e);
       }
    }
}

 

Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google

courses

TechVidvan Team

TechVidvan Team provides high-quality content & courses on AI, ML, Data Science, Data Engineering, Data Analytics, programming, Python, DSA, Android, Flutter, full stack web dev, MERN, and many latest technology.

Leave a Reply

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