• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Serialization

 
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
I was goin through Serialization! from KS & BB book. I came to know if superclass does not implement Serializable, when object(of subclass-implementing serializable) is read back, the states(inherited instance variables) that it inherited from its superclass are set to default.
I also saw an example and implemented it! however it is not givin me the desired RESULT.
import java.io.*;
class Animal{
int weight = 42;
}
class Dog extends Animal implements Serializable{
String name;
Dog(String n, int w){
name = n;
weight = w;
}
}
public class SuperNotSerail {
public static void main(String[] args){
Dog d = new Dog("test", 22);
System.out.println("before: "+d.name+" "+d.weight);
try{
File f = new File("c:/shivey/scjprob", "SuperNotSerial.txt");
FileOutputStream fos = new FileOutputStream(f);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(d);
oos.close();
//Now Taking Written Object Back
FileInputStream fis = new FileInputStream(f);
ObjectInputStream ois = new ObjectInputStream(fis);
ois.readObject();
ois.close();
}catch(Exception e){
e.printStackTrace();
}
System.out.println("after: "+d.name+" "+d.weight);
}
}

Both times the output is
before: test 22
after: test 22
I am not sure why? Have i done any mistake?
Pls, i have been always a lil in this subject(Serializable).
Thanks,
Shivey
 
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It looks like you didn't actually read the serialized object back into d. Instead of just

you need to do something like


Right now, your code is not modifying d at all, which is why you see no change after deserialization.
 
Shivey Upadhyay
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks!
I was
 
Eat that pie! EAT IT! Now read this tiny ad. READ IT!
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic