I'm writing a PreferedCustomer object to a .dat file using FileIOStreams and ObjectIOStreams. I'm practicing Inheritance so there is a simple class hierarchy.
PreferredCustomer.java inherits from Customer.java
Customer.java inherits from Person.java.
When I read my PreferredCustomer object from the .dat file, it calls the Person.java no arg constructor and sets the Name, Address, and PhoneNumber field to "". How do I prevent it from calling the no arg construct which resets the String values?
I have the project hosted on github. https://github.com/davidmistretta/CustomerObjectDAT
The code I believe needs to be reworked is in Consumers -> src -> CustomerDemo -> StoreConsumerObjects.java lines 30->40 (the try/catch statement below)
Main method which writes an object then reads an object
public static void main(String[] args)
{
try (FileOutputStream fos = new FileOutputStream("customers.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos)) {
PreferredCustomer pc = new PreferredCustomer("David Mistretta","943 Fakedale Way, Funnyvale, MO, 01337","978-000-0000","01A001");
pc.setBalance(550);
System.out.println("Object to input into customers.dat\n" + pc.toString() +"\n\n");
oos.writeObject(pc);
} catch (IOException e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream("customers.dat");
ObjectInputStream ois = new ObjectInputStream(fis)) {
PreferredCustomer pca = (PreferredCustomer) ois.readObject();
System.out.println("Object output from customers.dat\n" + pca.toString());
ois.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
The no arg constructor I wrote in Person.java (lines 28 -> 34)
public Person()
{
System.out.println("Person no arg construct");
m_name = "";
m_phoneNumber = "";
m_address = "";
}
Current output
Object to input into customers.dat
Preferred Customer
Name: David Mistretta
Address: 943 Fakedale Way, Funnyvale, MO, 01337
Phone Number: 978-000-0000
Customer Number: 01A001
Mailing List: true
Balance: 550.0
Discount: 0.05
Person no arg construct
Object output from customers.dat
Preferred Customer
Name:
Address:
Phone Number:
Customer Number: 01A001
Mailing List: true
Balance: 550.0
Discount: 0.05
I expect for the Name, Address, and Phone Number field to reflect the fields when they were input. I followed the instructions on how to store an object in a file here https://kodejava.org/how-do-i-store-objects-in-file/
If someone could point me in the right direction on how to handle this, it would be appreciated.