Home Database Mysql Tutorial J2SE中的序列化之继承_MySQL

J2SE中的序列化之继承_MySQL

Jun 01, 2016 pm 02:11 PM
public sequence inherit

J2SE

  当一个父类实现Serializable接口后,他的子类都将自动的实现序列化。

  以下验证了这一点:

  package Serial;
  import java.io.Serializable;
  public class SuperC implements Serializable {//父类实现了序列化
  int supervalue;
  public SuperC(int supervalue) {
  this.supervalue = supervalue;
  }
  public String toString() {
  return "supervalue: "+supervalue;
  }
  }

  public class SubC extends SuperC {//子类
  int subvalue;

  public SubC(int supervalue,int subvalue) {
  super(supervalue);
  this.subvalue=subvalue;
  }

  public String toString() {
  return super.toString()+" sub: "+subvalue;
  }
  }

  public class Test1 {

  public static void main(String [] args){
  SubC subc=new SubC(100,200);
  FileInputStream in=null;
  FileOutputStream out=null;
  ObjectInputStream oin=null;
  ObjectOutputStream oout=null;
  try {
   out = new FileOutputStream("Test1.txt");//子类序列化
   oout = new ObjectOutputStream(out);
   oout.writeObject(subc);
   oout.close();
   oout=null;

   in = new FileInputStream("Test1.txt");
   oin = new ObjectInputStream(in);
   SubC subc2=(SubC)oin.readObject();//子类反序列化
   System.out.println(subc2);
  } catch (Exception ex){
   ex.printStackTrace();
  } finally{
  …此处省略
  }
  }
  }

  运行结果如下:

  supervalue: 100 sub: 200

  可见子类成功的序列化/反序列化了。

  怎管让子类实现序列化看起来是一件很简单的事情,但有的时候,往往我们不能够让父类实现Serializable接口,原因是有时候父类是抽象的(这并没有关系),并且父类不能够强制每个子类都拥有序列化的能力。换句话说父类设计的目的仅仅是为了被继承。

  要为一个没有实现Serializable接口的父类,编写一个能够序列化的子类是一件很麻烦的事情。java docs中提到:

  “To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime. ”

  也就是说,要为一个没有实现Serializable接口的父类,编写一个能够序列化的子类要做两件事情:

  其一、父类要有一个无参的constructor;

  其二、子类要负责序列化(反序列化)父类的域。

  我们将SuperC的Serializable接口去掉,而给SubC加上Serializable接口。运行后产生错误:

  java.lang.Error: Unresolved compilation problem:
  Serializable cannot be resolved or is not a valid superinterface
  at Serial.SubC.(SubC.java:15)
  at Serial.Test1.main(Test1.java:19)
  Exception in thread "main"

  果真如docs中所说的一样,父类缺少无参构造函数是不行的。

  接下来,按照docs中的建议我们改写这个例子:

  public abstract class SuperC {
  int supervalue;
  public SuperC(int supervalue) {
  this.supervalue = supervalue;
  }
  public SuperC(){}//增加一个无参的constructor
  public String toString() {
   return "supervalue: "+supervalue;
  }
  }

  public class SubC extends SuperC implements Serializable {
  int subvalue;

  public SubC(int supervalue,int subvalue) {
   super(supervalue);
   this.subvalue=subvalue;
  }

  public String toString() {
   return super.toString()+" sub: "+subvalue;
  }

  private void writeObject(java.io.ObjectOutputStream out)
  throws IOException{
   out.defaultWriteObject();//先序列化对象
   out.writeInt(supervalue);//再序列化父类的域
  }
  private void readObject(java.io.ObjectInputStream in)
  throws IOException, ClassNotFoundException{
   in.defaultReadObject();//先反序列化对象
   supervalue=in.readInt();//再反序列化父类的域
  }
  }

  运行结果证明了这种方法是正确的。在此处我们用到了writeObject/ readObject方法,这对方法如果存在的话,序列化时就会被调用,以代替默认的行为(以后还要探讨,先了解这么多)。我们在序列化时,首先调用了ObjectOutputStream的defaultWriteObject,它使用默认的序列化行为,然后序列化父类的域;反序列化的时候也一样。

  归纳一下:

  目的 行为

  为一个实现Serializable接口的父类,编写一个能够序列化的子类 子类将自动的实现序列化

  为一个没有实现Serializable接口的父类,编写一个能够序列化的子类 1, 父类要有一个无参的constructor;2, 子类要先序列化自身,然后子类要负责序列化父类的域

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

What is the difference between the developer version and the public version of iOS? What is the difference between the developer version and the public version of iOS? Mar 01, 2024 pm 12:55 PM

Every year before Apple releases a new major version of iOS and macOS, users can download the beta version several months in advance and experience it first. Since the software is used by both the public and developers, Apple has launched developer and public versions, which are public beta versions of the developer beta version, for both. What is the difference between the developer version and the public version of iOS? Literally speaking, the developer version is a developer test version, and the public version is a public test version. The developer version and the public version target different audiences. The developer version is used by Apple for testing by developers. You need an Apple developer account to download and upgrade it.

How do inheritance and polymorphism affect class coupling in C++? How do inheritance and polymorphism affect class coupling in C++? Jun 05, 2024 pm 02:33 PM

Inheritance and polymorphism affect the coupling of classes: Inheritance increases coupling because the derived class depends on the base class. Polymorphism reduces coupling because objects can respond to messages in a consistent manner through virtual functions and base class pointers. Best practices include using inheritance sparingly, defining public interfaces, avoiding adding data members to base classes, and decoupling classes through dependency injection. A practical example showing how to use polymorphism and dependency injection to reduce coupling in a bank account application.

Solve PHP error: problems encountered when inheriting parent class Solve PHP error: problems encountered when inheriting parent class Aug 17, 2023 pm 01:33 PM

Solving PHP errors: Problems encountered when inheriting parent classes In PHP, inheritance is an important feature of object-oriented programming. Through inheritance, we can reuse existing code and extend and improve it without modifying the original code. Although inheritance is widely used in development, sometimes you may encounter some error problems when inheriting from a parent class. This article will focus on solving common problems encountered when inheriting from a parent class and provide corresponding code examples. Question 1: The parent class is not found. During the process of inheriting the parent class, if the system does not

Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Calculate interest on fixed deposits (FDs) and fixed deposits (RDs) using inherited Java program Aug 20, 2023 pm 10:49 PM

Inheritance is a concept that allows us to access the properties and behavior of one class from another class. The class that inherits methods and member variables is called a superclass or parent class, and the class that inherits these methods and member variables is called a subclass or subclass. In Java, we use "extends" keyword to inherit a class. In this article, we will discuss a Java program to calculate interest on fixed deposits and time deposits using inheritance. First, create these four Java files - Acnt.java − in your local machine IDE. This file will contain an abstract class ‘Acnt’ which is used to store account details like interest rate and amount. It will also have an abstract method 'calcIntrst' with parameter 'amnt' for calculating

Detailed explanation of C++ function inheritance: How to debug errors in inheritance? Detailed explanation of C++ function inheritance: How to debug errors in inheritance? May 02, 2024 am 09:54 AM

Inheritance error debugging tips: Ensure correct inheritance relationships. Use the debugger to step through the code and examine variable values. Make sure to use the virtual modifier correctly. Examine the inheritance diamond problem caused by hidden inheritance. Check for unimplemented pure virtual functions in abstract classes.

How to use polymorphism and inheritance in PHP to deal with data types How to use polymorphism and inheritance in PHP to deal with data types Jul 15, 2023 pm 07:41 PM

How to use polymorphism and inheritance to handle data types in PHP Introduction: In PHP, polymorphism and inheritance are two important object-oriented programming (OOP) concepts. By using polymorphism and inheritance, we can handle different data types more flexibly. This article will introduce how to use polymorphism and inheritance to deal with data types in PHP, and show their practical application through code examples. 1. The basic concept of inheritance Inheritance is an important concept in object-oriented programming. It allows us to create a class that can inherit the properties and methods of the parent class.

Packaging technology and application in PHP Packaging technology and application in PHP Oct 12, 2023 pm 01:43 PM

Encapsulation technology and application encapsulation in PHP is an important concept in object-oriented programming. It refers to encapsulating data and operations on data together in order to provide a unified access interface to external programs. In PHP, encapsulation can be achieved through access control modifiers and class definitions. This article will introduce encapsulation technology in PHP and its application scenarios, and provide some specific code examples. 1. Encapsulated access control modifiers In PHP, encapsulation is mainly achieved through access control modifiers. PHP provides three access control modifiers,

See all articles