printing in the same line in java

后端 未结 4 1801
暖寄归人
暖寄归人 2020-12-12 05:37

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(){
        Syst         


        
相关标签:
4条回答
  • 2020-12-12 06:09

    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";
    }
    
    0 讨论(0)
  • 2020-12-12 06:11

    Do not do println on the base class use print instead

    0 讨论(0)
  • 2020-12-12 06:26

    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

    • Object.toString()

    Related questions

    • toString() in Java
    • Is toString() only useful for debugging?
    • when to use toString() method
    0 讨论(0)
  • 2020-12-12 06:27

    replace println with System.out.print

    0 讨论(0)
提交回复
热议问题