java中序列化对继承的影响

今天学习写个即时通信工具,遇到了对象序列化对继承影响的问题。

定义了消息对象:

class Message

{

  protected byte type;

  public byte getType(){

    return this.type;

  }

}

 

class LoginMessage extends Message implements Serializable

{

  public LoginMessage(){

    this.type=1;

  }

}

 

客户端的代码:

public class ClientTest {
public static void main(String[] args){
    try{
        Socket s=new Socket("localhost",9000);
        OutputStream os=s.getOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(os);
        oos.writeObject(new LoginMessage());
    }
    catch(IOException e){
        e.printStackTrace();
    }
}
}

服务器端的代码:

public class ServerTest {
    public static void main(String[] args){
        try{
            ServerSocket s=new ServerSocket(9000);
            Socket incoming=s.accept();           
            ObjectInputStream in=new ObjectInputStream(incoming.getInputStream());
                System.out.println(((Message)in.readObject()).getType());
                in.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

 

结果程序输出0,而不是1.

分析:因为父类没有实现序列化,导致其子类序列化时继承自父类的属性不能被保存。Java doc中明确指出,如果一个类继承了一个非Serializable类时,如果想在序列化中保存父类的属性,则需要实现额外的代码显式地存储父类的属性值。

在自己的代码中,可以将父类实现序列化,子类将自动实现序列化。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值