简体   繁体   中英

Can I make a DataOutputStream method for an abstract class and use this for the subclasses?

I have a book class:

public abstract class Book
{
private String author, title;
private int pages;
private double price;
Book next;

public Book( String f, String t, int sider, double p )
{
    author = a;
    title = t;
    pages = pa;
    price = p;
    next = null;
}

And subclasses like novels, textbooks and so forth. I need a method to write these to a file with DataOutputStream. I made this code below, but I'm not sure if I'm on the right path. How would I use this in a subclass?

public void writeObjectToFile()
{
    try
    {
        FileOutputStream fos = new FileOutputStream("book.something");
        DataOutputStream dos = new DataOutputStream(fos);

        dos.writeUTF(author);
        dos.writeUTF(title);
        dos.writeInt(pages);
        dos.writeDouble(price);         


    }catch (IOException e){
        e.printStackTrace();
    }
}

Let's say the textbook class is like this:

class Textbook extends Book
{
private String subject;

public Textbook( String a, String t,int pa, double p, String sub )
    {
    super( a, t, pa, p );
    subject = sub;
}

Any ideas? I'm not allowed to use ObjectOutputStream .

The method should take the OutputStream as argument, instead of creating it itself.

This way, subclasses can start by calling the super method to write the superclass fields, and callers can choose where to write the data rather than being forced by the book class to use a file at a specific location.

The method should also throw the IOException, rather than ignoring it. This way, the caller can do what he wants to handle it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM