-1

I have a class named Database that is defined and contains some data in it's fields.

Now, I create an object of that class as

Database d1 = new Database();

Now, I make changes to those data values of d1 such that whenever I create another object of Database say 'Database d2', this object has the updated values of the data. That means, we need to be able to change the class definition using an object of that class.

Can this be achievable?

  • 1
    The title of your question (`Serialization`) is a mechanism for reading/writing `Object`(s) to/from `Stream`(s). The body of your question seems to be about implementing a [shallow copy](http://stackoverflow.com/q/184710/2970947). What are you trying to do? – Elliott Frisch Dec 16 '15 at 04:36
  • I guess using the Static keyword? – Mitchell Santner Dec 16 '15 at 04:36

2 Answers2

2

I think you might want to implement a copy constructor in your java code, you can do this:

class Database{

    Filed field; // some field

    Database(){
    }

    Database(Database db){  // copy constructor
        this.field  = db.field.clone();
    }
}

Database d2 = new Database(d1)

Then d2 will have all the filed updated by d1.

VicX
  • 721
  • 8
  • 13
0

"That means, we need to be able to change the class definition using an object of that class."

Really? You don't change the values in the fields of an instance of a class by changing the classes definition. The class definition is ... the source code / compiled bytecodes.

But if you DO change the class definition, you are liable to find that the new version of the class cannot deserialize instances that were serialized using the old version of the class. (Details depend on the precise nature of the changes ...)

More generally, Java serialization is not a good option for databases:

  • it is slow,
  • it is not incremental (if you are loading / saving the entire database)
  • it doesn't scale (if you are loading the entire database into memory)
  • it doesn't support querying (unless you load the entire database into memory and implement the queries in plain Java), and
  • you run into lots of problems if you need to change the "schema"; i.e. the classes that you are serializing / deserializing.

But modulo those limitations, it will work; i.e. it is "achievable".


And if you are really talking about how to change the state of your in-memory Database object, or how to create a new copy from an existing out then:

  • implement / use getters, setters and / or other methods in the Database class,
  • implement a copy constructor, factory method or clone method that copies the Database object state ... to whatever depth you need.

All very achievable (simple "Java 101" level programming), though not necessarily a good idea.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216