

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Externalizable Interface in Java
Externalization is used whenever we need to customize serialization mechanism. If a class implements an Externalizable interface then, object serialization will be done using writeExternal() method. Whereas at receiver's end when an Externalizable object is a reconstructed instance will be created using no argument constructor and then the readExternal() method is called.
If a class implements only Serializable interface object serialization will be done using ObjectoutputStream. At the receiver's end, the serializable object is reconstructed using ObjectInputStream.
Below example showcases usage of Externalizable interface.
Example
import java.io.Externalizable; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; public class Tester { public static void main(String[] args) { Employee e = new Employee(); e.name = "Reyan Ali"; e.age = 30; try ( FileOutputStream fileOut = new FileOutputStream("test.txt"); ObjectOutputStream out = new ObjectOutputStream(fileOut); ) { out.writeObject(e); }catch (IOException i) { System.out.println(i.getMessage()); } try ( FileInputStream fileIn = new FileInputStream("test.txt"); ObjectInputStream in = new ObjectInputStream(fileIn); ) { e = (Employee)in.readObject(); System.out.println(e.name); System.out.println(e.age); } catch (IOException i) { System.out.println(i.getMessage()); } catch (ClassNotFoundException e1) { System.out.println(e1.getMessage()); } } } class Employee implements Externalizable { public Employee(){} String name; int age; public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeInt(age); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = (String)in.readObject(); age = in.readInt(); } }
This will produce the following result −
Output
Reyan Ali 30
- Related Questions & Answers
- What is Externalizable in Java?
- What is the difference between Externalizable and Serializable interfaces in Java?
- Interface in Java
- Nested interface in Java
- ConcurrentMap Interface in java
- Deque interface in Java
- Marker interface in Java
- Function interface in Java
- BinaryOperator Interface in Java
- IntUnaryOperator Interface in Java
- Java Interface methods
- Why an interface cannot implement another interface in Java?
- Interface enhancements in Java 8
- Set Interface in Java Programming
- SortedMap Interface in Java Programming
Advertisements