I’m doing a little homework on Java, but I’m not good at it and I’m having issues trying to use XMLEncoder to store an App objects to a file.
In short my App has and abstract class called animal and another ones that extend the previous one called dogand cat. In my main App I’ve a static method to create new animals that adds the new animal object to a static ArrayList of type animal: public static ArrayList<animal> animalArray = new ArrayList<animal>();
Creating an animal at
kingdom.java:
private static void newAnimal(ArrayList<animal> animalArray) {
System.out.print(" Enter a name for the dog > ");
animalArray.add(new dog(keyboard.nextLine()));
System.out.println(" New dog with name " + animalArray.get(animalArray.size()-1).getName() + ".\n");
try {
FileOutputStream afos = new FileOutputStream("animals.xml");
XMLEncoder encoder = new XMLEncoder(afos);
encoder.writeObject(animalArray.get(animalArray.size()-1));
encoder.close();
} catch(IOException ioe){
System.out.print("[ERROR!]");
}
}
My abstract animal class:
animal.java:
public abstract class animal {
private static int alloc = 0;
protected int id;
private String name;
animal() {
alloc++;
id = alloc;
}
public void play() {
System.out.print(" The animal (" + this.id + ") " + this.name + " is now playing... ");
}
public void setName(String lname) {
this.name = lname;
}
public String getName() {
return this.name;
}
public static int countAnimals() {
return alloc;
}
}
Now, my dog class:
dog.java:
public class dog extends animal {
dog(String theName) {
this.setName(theName);
}
@Override
public void play() {
super.play();
System.out.println(" Dog Stuff!");
}
}
When I try to run the code I get:
java.lang.InstantiationException: dog
Continuing ...
java.lang.Exception: XMLEncoder: discarding statement XMLEncoder.writeObject(dog);
Continuing ...
What am I missing? Thank you 😉
You should use as following:
encoder.writeObject(animalArray.get(animalArray.size()-1).getName());
The Dog object itself can’t be saved into XMLEncoder.
Thx.