📜 ⬆️ ⬇️

java.io.Serializable and inheritance

What is serialization can be read in an excellent article by Evgeny Matyushkin .

I will note the case with this miracle of technology in the aspect of class inheritance. The Serializable interface does not require any action from the developer; however, it is important to remember that the internal mechanism serializes only the fields of this class and the heirs fields, and the fields of the parent will be initialized using the constructor without parameters .


I.e:
')
import java.io.*;

class GrantParent implements Serializable {

private String grandParentId;

public String getGrandParentId() {
return grandParentId;
}

public void setGrandParentId( String grandParentId) {
this .grandParentId = grandParentId;
}
}

class Parent extends GrantParent {

private String parentId;

Parent() {
parentId = "Parent Default Value" ;
}

public String getParentId() {
return parentId;
}

public void setParentId( String parentId) {
this .parentId = parentId;
}
}


class Child extends Parent {

private String id;

public String getId() {
return id;
}

public void setId( String id) {
this .id = id;
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder ();
sb.append( "Child" );
sb.append( "{id='" ).append(id).append( '\'' );
sb.append( ", parentId='" ).append(getParentId()).append( '\'' );
sb.append( ", grandParentId='" ).append(getGrandParentId()).append( '\'' );
sb.append( '}' );
return sb.toString();
}
}


* This source code was highlighted with Source Code Highlighter .


Now, by declaring the interface for one class of hierarchy, we obtain:

Source: https://habr.com/ru/post/50259/


All Articles