Hey all:) I'm learning Java and I'm having a little trouble on a polymorphic write-to-file function. Let me quickly explain my project:

I have an abstract class Mammal, with non-abstract children Horse, Cow etc.

I have a Main program that creates a couple Horses and Cows, and store these in a Mammal array.

Now the Mammal class and its children have a function called WriteData(), and the plan is that in my Main program I should be able to call this function polymorphic like array[index].WriteData(), and each Horse and Cow should write their personal info on a separate line to an output file. (so one line for each object).

However, I'm having trouble figuring out where to place the code:

Printwriter output = new PrintWriter (new FileWriter(new File("out.dat")));

Should this be placed in the Mammal class' WriteData() function? (which is not abstract, but has basic info on each Horse and Cow). The problem with this approach is that every time I call array[index].WriteData() the printwriter code line would be run once for each object, and I don't know if that's the right way to do it. Also, the Main program won't be able to call output.close, since it can't see the abstract class Mammal's variables.

My Plan B was to place the Printwriter code in the Main program, then however, the Horse and Cow won't be able to use it :(

So I'm at a loss here, not being able to see how I should solve this. Any help is much appreciated:)

Recommended Answers

All 2 Replies

I would pass the PrintWriter as a parameter to all the WriteData methods. So it's created and closed in the same place as the loop (eg your Main program).

Worked like a charm :) Thanks a lot man:)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.