954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Polymorphic write-to-file with abstract inheritance problem (not as bad as it sounds)

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:)

lacoffo
Newbie Poster
5 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

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).

JamesCherrill
Posting Genius
Moderator
6,373 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

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

lacoffo
Newbie Poster
5 posts since Mar 2011
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: