0

I have to make only one show() method

public static void main(String[] args) {
    show(new String("MATH"));
    show(new StringBuilder("MINUS"));
    show(new StringBuffer("%@&"));
}
9
  • 2
    Hint: look at the documentation for those types. Can you see anything they have in common in terms of superclass or interfaces they implement? Commented May 18, 2022 at 6:45
  • 1
    String, StringBuilder and StringBuffer. What do they all implement? Commented May 18, 2022 at 6:51
  • 5
    Links to documentation: String, StringBuilder, and StringBuffer. What is a common interface that would make sense to use in this scenario? Commented May 18, 2022 at 6:52
  • 4
    Near the top of each Javadoc page, there is an "All Implemented Interfaces" section. Look at the implemented interfaces. There's one all three have in common that represents a sequence of characters. Commented May 18, 2022 at 6:58
  • 1
    @Jean change your show method to show(Charsequence stringToPrint) because all 3 String, StringBuilder, and StringBuffer implement Charsequence, so you can just pass that instead. That way, you can pass all of them to a single method. Commented May 18, 2022 at 7:04

1 Answer 1

1

String, StringBuilder, StringBuffer all implement CharSequence. They share some similarities they must get from that interface(read more about interfaces in Java, you can think about them as a kind of contract - classes that implement an interface must implement its methods), so you can write:

    show(CharSequence someString){
    //something to do
    }

because:

    CharSequence string1 = new String();
    CharSequence string2 = new StringBuilder(); 
    CharSequence string3 = new StringBuffer();

When in doubt about which classes implements which interfaces or extends which classes try searching in docs.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.