Is my inheritance code correct? - java

So basically, I am doing this school project, and I have a super class called Person, and two subclasses (employees and clients) which extends class Person. When I run eighter subclass and for example when I add an employee, store the data in a .dat file, exit the program and re-run it, all the data stored before is set to a blank String. I hink that this is coming from the parameterless constructor in class Person, but that is the way I learnt to code it.
Super class:
import java.util.*;
public class Person{
String name, sname, dob, address, tel, mob;
public Person(){
name = ""; //I tried removing these statements, but then the data returned was null
sname = "";
dob = "";
address = "";
tel = "";
mob = "";
}
public Person(String name, String sname, String dob, String address, String tel, String mob){
this.name = name;
this.sname = sname;
this.dob = dob;
this.address = address;
this.tel = tel;
this.mob = mob;
}
Sub-class:
import java.io.*;
import java.util.*;
public class Employee extends Person implements Serializable{
private String empid;
private String valn = "[a-zA-Z ]+";
private String vala = "[a-zA-Z0-9, ]+";
private String valt = "[2][17][0-9]{6}";
private String valm = "[79][9][0-9]{6}";
private String valmm = "[7][7][0-9]{6}";
private String chkeid = "[0-9]{4}[E]";
public Employee(){
super();
empid = "";
}
public Employee(String name, String sname, String dob, String address, String tel, String mob,String empid){
super(name, sname, dob, address, tel, mob);
this.empid = empid;
}
public void setId(String empid){
this.empid = empid;
}
public String getId(){
return empid;
}
public String ToString(){
return "Emloyee Name: " + name + " " + sname + " " +
"\nAddress: " + address +
"\nDate of Birth: " + dob +
"\nTelephone Number: " + tel +
"\nMobile Number: " + mob +
"\nEmployee ID: " + empid;
}//Other methods...
Code for file saving:
File stock = new File("C:/Users/david/Desktop/Stock.dat");
File employee = new File("C:/Users/david/Desktop/Employee.dat");
File clients = new File("C:/Users/david/Desktop/Clients.dat");
try{
if(stock.exists() == true){
FileInputStream inFileStream = new FileInputStream (stock);
ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream);
stck = (Vector <Stock>)inObjectStream.readObject();
inObjectStream.close();
}else{
FileOutputStream outFile = new FileOutputStream(stock);
ObjectOutputStream outObject = new ObjectOutputStream(outFile);
outObject.close();
}
}catch (IOException io ){
System.out.println ("Error Loading Stock Database!");
sc.next();
}catch (ClassNotFoundException c){
System.out.println ("Error Loading Database! Class not found!!");
sc.next();
}
try{
if(employee.exists() == true){
FileInputStream inFile = new FileInputStream (employee);
ObjectInputStream inObject = new ObjectInputStream(inFile);
emp = (Vector <Employee>)inObject.readObject();
inObject.close();
}else{
FileOutputStream outStr = new FileOutputStream(employee);
ObjectOutputStream outObj = new ObjectOutputStream(outStr);
outObj.close();
}
}catch (IOException io ){
System.out.println ("Error Loading Employee Database!");
sc.next();
}catch (ClassNotFoundException c){
System.out.println ("Error Loading Database! Class not found!");
sc.next();
}
try{
if(clients.exists() == true){
FileInputStream in = new FileInputStream (clients);
ObjectInputStream inObjct = new ObjectInputStream(in);
clt = (Vector <Clients>)inObjct.readObject();
inObjct.close();
}else{
FileOutputStream out = new FileOutputStream(clients);
ObjectOutputStream outObjct = new ObjectOutputStream(out);
outObjct.close();
}
}catch (IOException io ){
System.out.println ("Error Loading Clients Database!");
sc.next();
}catch (ClassNotFoundException c){
System.out.println ("Error Loading Database! Class not found!");
sc.next();
}
//at the end of the runner class.
try{
FileOutputStream outFile = new FileOutputStream(stock);
ObjectOutputStream outObject = new ObjectOutputStream(outFile);
outObject.writeObject(stck);
outObject.close();
}catch(IOException e){
System.out.println ("Error writing to Database!");
sc.next();
}
try{
FileOutputStream outFile = new FileOutputStream(employee);
ObjectOutputStream outObject = new ObjectOutputStream(outFile);
outObject.writeObject(emp);
outObject.close();
}catch(IOException e){
System.out.println ("Error writing to Database!");
sc.next();
}
try{
FileOutputStream outF = new FileOutputStream(clients);
ObjectOutputStream outObjct = new ObjectOutputStream(outF);
outObjct.writeObject(clt);
outObjct.close();
}catch(IOException e){
System.out.println ("Error writing to Database!");
sc.next();
}

Employee is serializable, but Person is not. What that means is that the fields inherited from Person are not being serialized (that is, they are not being written to the ObjectOutputStream) and will not be filled in during deserialization (that is, reading from an ObjectInputStream).
The easiest way to fix this is to make Person implement Serializable. Note that the interface is inherited, so if you do make that change, you can safely remove implements Serializable from the Employee class.
If that isn't an option, you will have to do the work yourself in your Employee class. That's rather involved for someone new to Java, so I'd rather not clutter this answer with the details, but if you need to go this route I can elaborate.

Your code seems correct in terms of inheritence, the "problem" seems to be in the way you're using it.
How are you instanciating each employee?
Are you using the constructor with parameters? You have to use that one when you re-run your program, otherwise you'll be instantiating blank empoloyees as you describded.

To serialize members of super class this Person class should also implements Serializable.
public class Person implements Serializable {
...
As described here then Employee class will automatically implements Seralizable.

Related

how to fix up code with java display

import java.util.Scanner;
import java.util.Formatter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
class Enrolment{
public static void main(String[] args)
{
System.out.println("/*-------------------------------------");
System.out.println("My name: XIANGYU QIAO");
System.out.println("My student number: 5089864");
System.out.println("My email address: xq907#uowmail.edu.au");
System.out.println("Assignment number: 2");
System.out.println("-------------------------------------*/");
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
class Student{
private static Formatter outStream;
private static Scanner inStream;
public Student() throws IOException
{
outStream = new Formatter(new File("student1.txt"));
String fullName = "David Black";
String email = "davblk#ipw.edu.au";
String course = "1853E";
sNumber = 375428;
outStream.format("%s %s %s %i", fullName, email, course, sNumber);
outStream.close();
inStream = new Scanner( new File("student1.txt"));
String Fullname = inStream.next();
String Email = inStream.next();
String Course = inStream.next();
int Studentnumber = inStream.nextInt();
inStream.close();
}
public void displayStudInfo()
{
System.out.print("\nStudent " + Fullname + Email + Course+ Studentnumber);
}
}
class Subject{
private static Formatter outStream;
private static Scanner inStream;
public Subject() throws IOException
{
outStream = new Formatter(new File("subject1.txt"));
String sCode = "CSIT455";
String session = "Autmn";
int year = 2017;
outStream.format("%s %s %i", sCode, session, year);
outStream.close();
inStream = new Scanner( new File("subject1.txt"));
String Subjectcode = inStream.next();
String Session = inStream.next();
int Year = inStream.nextInt();
inStream.close();
System.out.print("\nEnrolment " + Subjectcode + session + Year);
}
}
i am trying to create a file of student information and display it but i could not find a way to do that. could anyone help me to fix the code?
i am asked to display the student information in class Enrolment(main method here)and subject information that is given in class Student and Subject.i have no idea how to link these three things though it requires to use displayStudInfo method in class Student and displaySubjectInfo in class Subject.
If I correctly understand, you cannot access properties from constructor in displayStudInfo method. So assigning those properties to class properties will resolve the issue.
class Student {
private final String fullname;
private final String email;
private final String course;
private final int studentNumber;
public Student() throws IOException {
writeStudent();
Scanner inStream = new Scanner(new File("student1.txt"));
fullname = inStream.next();
email = inStream.next();
course = inStream.next();
studentNumber = inStream.nextInt();
inStream.close();
}
private void writeStudent() throws FileNotFoundException {
Formatter outStream = new Formatter(new File("student1.txt"));
outStream.format("%s %s %s %i", "David Black", "davblk#ipw.edu.au", "1853E", 375428);
outStream.close();
}
public void displayStudInfo() {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}
}
If you do not want to add any more class prop, you will need to ad arguments to your method:
public void displayStudInfo( String fullname,String email,String course, int studentNumber) {
System.out.print("\nStudent " + fullname + email + course + studentNumber);
}

Writing and Reading to/from a file Objects stored in ArrayList

This is a simple example where I'm trying to write and read Objects stored in ArrayList to/from file.
Writing file is working. Reading file is working only for first Object in my ArrayList. How should I make this into a loop?
I tried with something like:
`while(ois !=null) {
Person result = (Person) ois.readObject();
persons.add(result);
}
but it's not working.
Here is full test code:
public class Data {
static ArrayList<Person> persons = new ArrayList<Person>();
public static void savePersons() throws IOException{
FileOutputStream fout = null;
ObjectOutputStream oos = null;
/** Make 5 'Person' object for examle */
for(int i = 0; i<5; i++){
Person personTest = new Person("name", "surname", "email", "1234567890");
persons.add(personTest);
}
try{
fout = new FileOutputStream("C:\\data.dat", true);
oos = new ObjectOutputStream(fout);
oos.writeObject(persons);
System.out.println("Saving '" +persons.size()+ "' Object to Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR");
} finally {
if(oos != null){
oos.close();
}
}
}
public static void loadPersons() throws IOException{
FileInputStream fis = null;
ObjectInputStream ois = null;
/** Clean 'persons' array for TEST of load data*/
persons.removeAll(persons);
try {
fis = new FileInputStream("C:\\data.dat");
ois = new ObjectInputStream(fis);
Person result = (Person) ois.readObject();
persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" +persons.size()+ "' Object from Array");
System.out.println("persons.size() = " +persons.size());
System.out.println("loadPersons() = OK");
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR");
} finally {
if(ois != null){
ois .close();
}
}
}
}
Person class:
public class Person implements Serializable {
private String name;
private String surname;
private String mail;
private String telephone;
Person person;
public Person(String n, String s, String m, String t){
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}}
Main class:
public class Test {
public static void main(String[] args) {
Data.savePersons();
Data.loadPersons();
}}
Here you go... please take note of the following:
YES, Chetan Jadhav CD's suggestion WORKS. B
Use an IDE like Eclipse to help you debug your code and make your life easier.
Be clear about what your error is (show stack trace, etc..) Note the modification to your catch clause that prints:
System.out.println("Saving ERROR: " + ex.getMessage());
Put all your code in one file before you ask for help to make everyone's life easier.
Make each 'Person' at least someone unique by numbering them with your index Use .ser for a serializable file, rather than .dat
import java.util.List;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
public class Data {
private static final String SER_FILE = "C:\\view\\data.ser";
static List<Person> persons = new ArrayList<Person>();
public static void main(String[] args) throws IOException {
Data.savePersons();
Data.loadPersons();
}
public static void savePersons() throws IOException {
/** Make 5 'Person' object for example */
for (int i = 0; i < 5; i++) {
Person personTest = new Person("name" + i, "surname" + i, "email" +i, "1234567890-" +i);
persons.add(personTest);
}
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SER_FILE, true));) {
oos.writeObject(persons);
System.out.println("Saving '" + persons.size() + "' Object to Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("savePersons() = OK");
} catch (Exception ex) {
System.out.println("Saving ERROR: " + ex.getMessage());
}
}
public static void loadPersons() throws IOException {
/** Clean 'persons' array for TEST of load data */
persons.removeAll(persons);
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SER_FILE));){
persons = (List<Person>) ois.readObject();
//persons.add(result);
System.out.println("-------------------------");
System.out.println("Loading '" + persons.size() + "' Object from Array");
System.out.println("persons.size() = " + persons.size());
System.out.println("loadPersons() = OK");
persons.stream().forEach(System.out::println);
} catch (Exception e) {
System.out.println("-------------------------");
System.out.println("Loading ERROR: " + e.getMessage());
}
}
}
class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String surname;
private String mail;
private String telephone;
public Person(String n, String s, String m, String t) {
name = n;
surname = s;
mail = m;
telephone = t;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getMail() {
return mail;
}
public String getTelephone() {
return telephone;
}
#Override
public String toString() {
return "Person [name=" + name + ", surname=" + surname + ", mail=" + mail + ", telephone=" + telephone + "]";
}
}

Creating an object array based on the contents of a file

I have a text file that looks like this.
BEGINNING OF LIST
Name: Janet
Age: 21
Birthday month: April
END OF LIST
BEGINNING OF LIST
Name: Peter
Age: 34
Birthday month: January
END OF LIST
So I want to grab info and put it into an object array. it is an extensive list and I am using the delimiters beginning of list and end of list to delimit the content.
How can I store these items in an object array?
I would suggest you create a class first for storing the information, with name, age, and birthday month attributes. It's a very good practice to override the toString() method so you can print out the class neatly.
Then you can check for each line whether it contains information about the name, age, or birthday month through splitting each line into an array of words, and checking for the information.
Once the line reads "END OF LIST", you can add a class Person with the parameters to the ArrayList.
For the example I used "people.txt" as the file (make sure you place the text document outside of the src folder which contains your .java files).
Main.java
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args)
{
BufferedReader bufferedReader = null;
FileReader fileReader = null;
String name = null;
String age = null;
String month = null;
List<Person> people = new ArrayList<Person>();
try
{
String fileName = "people.txt";
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
String[] information = line.split(" ");
if (Arrays.asList(information).contains("Name:"))
{
name = information[1];
}
if (Arrays.asList(information).contains("Age:"))
{
age = information[1];
}
if (Arrays.asList(information).contains("month:"))
{
month = information[2];
}
if (line.equals("END OF LIST"))
{
people.add(new Person(name, age, month));
name = "";
age = "";
month = "";
}
}
for (Person person : people)
{
System.out.println(person);
System.out.print("\n");
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
catch (IOException ex)
{
System.out.println("Error reading people.txt");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
if (fileReader != null)
{
try
{
fileReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
}
}
Person.java
public class Person {
private String name;
private String age;
private String birthday;
public Person(String name, String age, String birthday)
{
this.name = name;
this.age = age;
this.birthday = birthday;
}
#Override
public String toString()
{
String information = "Name: " + name + "\nAge: " + age + "\nBirthday: " + birthday;
return information;
}
}

File Reader Format

This project I'm working on, here is the function which write data's in to file :
public void writetofile(){
String bucky[]={custname,custlname,agee,address,id};
for(int i = 0; i < bucky.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("records.txt", true))) {
String s;
s = bucky[i];
bw.write(s);
bw.newLine();
bw.flush();
}
catch(IOException ex) {
JOptionPane.showMessageDialog(null, "Error In File");
}
}
};
and there is another function defined which reads data's from file ,
public void filereader (){
int i=0;
Object[] options = {"OK"};
try
{
FileInputStream in = new FileInputStream("records.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
StringBuffer sb = new StringBuffer();
while((strLine = br.readLine())!= null)
{
sb.append(strLine +"\n");
}
JOptionPane.showMessageDialog( null, sb.toString());
}catch(Exception e){
JOptionPane.showOptionDialog(null, "Error", "Customers", JOptionPane.PLAIN_MESSAGE,JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
}
};
and the problem is , let's say I want to create an account for a customer in my project , so few questions were asked such as name , last name , gender , etc. and all those info's have been saved , but when I try to read files all the data's will appear in no format , I want them to be appear in the proper way like this :
customer name : Michelle ,
gender : Female ;
but right now it appears as this :
michelle ,
female ,
You can construct the desired output first and callbw.write(s); only once
or follow R.J 's suggestion. Put everything to an object and override toString methid of that class. This will be the perfect way of solving your problem
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JOptionPane;
public class Customer
{
private final String firstName;
private final String lastName;
private final String address;
private final int age;
private final int id;
public Customer(String firstName, String lastName, String address, int age,
int id)
{
super();
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.age = age;
this.id = id;
}
#Override
public String toString ()
{
return "Customer [firstName=" + firstName + ", lastName=" + lastName
+ ", address=" + address + ", age=" + age + "]";
}
public static void main (String[] args)
{
}
public void writetofile (String custname, String custlname, int agee,
String address, int age)
{
Customer customer = new Customer(custname, custlname, address, age, id);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(
"records.txt", true)))
{
String s = customer.toString();
bw.write(s);
bw.newLine();
bw.flush();
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(null, "Error In File");
}
}
}

Deserializing an Employee Record in Java

Below is a program that should deserialize the record of employees. It does deserialize the first record but it does not deserialize the other records added by the user.
import java.io.*;
import java.util.*;
public class Employee implements Serializable {
private Object name;
private Object address;
private Object ssn;
private Object eadd;
private Object number;
private void writeObject(ObjectOutputStream os) throws IOException {
os.defaultWriteObject();
}
private void readObject (ObjectInputStream is) throws IOException, ClassNotFoundException {
is.defaultReadObject();
}
public static void addEmployee() {
try {
Employee e = new Employee();
BufferedReader buffer = new BufferedReader(new InputStreamReader(System.in));
FileOutputStream fileOut = new FileOutputStream("employee.ser", true);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
System.out.println("Name: ");
e.name = buffer.readLine();
System.out.println("Address: ");
e.address = buffer.readLine();
System.out.println("SSN: ");
e.ssn = buffer.readLine();
System.out.println("Email: ");
e.eadd = buffer.readLine();
System.out.println("Number: ");
e.number = buffer.readLine();
out.writeObject(e +"#");
out.close();
fileOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void deserializeAll() throws ClassNotFoundException {
Employee e = null;
try {
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.ssn);
System.out.println("Email: " + e.eadd);
System.out.println("Number: " + e.number);
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static void main(String[] args) throws ClassNotFoundException {
int choice;
Scanner input = new Scanner (System.in);
do {
System.out.println("[1] Add an employee.");
System.out.println("[2] Deserialize all.");
choice = input.nextInt();
switch (choice) {
case 1: addEmployee(); break;
case 2: deserializeAll(); break;
default: System.exit(0);
}
} while (choice != 3);
}
}
The # is the delimeter per record.
You can't append to an ObjectOutputStream. Once you have closed it you cannot add to it.
Instead you either need to re-write the entire file or use a different file format (one which allow appending of data)
BTW: This doesn't write the Object
out.writeObject(e +"#");
It writes the e.toString() + "#" which is a String when you deserialize it, not the original object.
I would make your field types String instead of Object.
And I would delete your writeObject and readObject methods as they don't do anything.

Categories

Resources