Learn Java Tutorial for Beginners (Video), Part 48: Transient

We'll finish off our videos on serialization in Java with a look at the transient keyword, plus some stuff about how constructors behave on deserialization and the notorious serial version UID.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen. Don't forget to change to HD also if the video appears fuzzy.



Code for this tutorial:


Person.java:

 
import java.io.Serializable;

public class Person implements Serializable {
    
    private static final long serialVersionUID = -1150098568783815480L;
    
    private transient int id;
    private String name;
    
    private static int count;
    
    public Person() {
        System.out.println("Default constructor");
    }
    
    public Person(int id, String name) {
        this.id = id;
        this.name = name;
        
        System.out.println("Two-argument constructor");
    }
    
    public static int getCount() {
        return count;
    }

    public static void setCount(int count) {
        Person.count = count;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + "] Count is: " + count;
    }
}

// www.caveofprogramming.com

 

WriteObjects.java:

 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class WriteObjects {

    public static void main(String[] args) {
        System.out.println("Writing objects...");

        try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("test.ser"))) {

            Person person = new Person(7, "Bob");
            Person.setCount(88);
            os.writeObject(person);
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

 

ReadObjects.java:

 
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;

public class ReadObjects {

    public static void main(String[] args) {
        System.out.println("Reading objects...");
        
        try (ObjectInputStream os = new ObjectInputStream(new FileInputStream("test.ser"))) {

            Person person = (Person)os.readObject();
            System.out.println(person);
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}