0

I have a base class called Items and 3 derived classes, and within the Items base class i have a print function of the form

public void print(){
        System.out.println("ID " + id + " Title " + title + " <" + year + "> ");
    }

and within every derived class I call the Items print function through super.print(); which is followed by a specific print function relating to the derived class.

My problem is, whenever the printing is executed from one of the derived classes the printed text is not on the same line. So super.print() will be in the line above the derived class print function. How do I get them both to be on the same line?

silent
  • 2,836
  • 10
  • 47
  • 73

4 Answers4

4

You can't safely retract a newline after it's been printed (outputting a backspace character works depending on the terminal, but you really don't want to do that). I think probably the logical way to architect this is have one superclass function:

public void print() {
    System.out.println(toString());
}

And then override toString as needed:

Superclass

public String toString() {
    return "ID " + id + " Title " + title + " <" + year + "> ";
}

Subclass

public String toString() {
    return super.toString() + " ... more stuff";
}
Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
2

Do not do println on the base class use print instead

Itay Karo
  • 17,924
  • 4
  • 40
  • 58
  • I imagine he wants the function to output the newline when called, but only if it's directly called by a user instead of a subclass -- i.e. he doesn't want to need to do `foo.print(); System.out.println();` – Michael Mrozek May 31 '10 at 06:05
  • 1
    Actually - I do agree with. Overriding ToString() is a better way. – Itay Karo May 31 '10 at 06:17
2

replace println with System.out.print

Ryan Fernandes
  • 8,238
  • 7
  • 36
  • 53
2

It looks like overriding toString() is more appropriate, here. You can then control the printing where it's needed, and it can go to System.out, or a file, or a logger, and everything else.

@Override public String toString() {
   return String.format("ID %s Title %s <%d> ", id, title, year);
}

Then in the child classes:

@Override public String toString() {
   return super.toString() + " whatever";
}

API links

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623