Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
448 views
in Technique[技术] by (71.8m points)

inheritance - printing in the same line in java

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...