3

In java, we can narrow the return type and the throws exception type (or even erase the throws clause) :

abstract class A
{
  abstract CharSequence getName() throws NameNotAvailableException;
}

class B extends A
{
  String getName()
  {
    return "foo";
  }
}

But, what about parameter types (if A takes a T, then why not B takes ? super T) as in :

abstract class A
{
  abstract void setName(final String name);
}

class B extends A
{
  void setName(final CharSequence name)
  {

  }
}

Let's consider this piece of code which i think is completely logical to me :

void handleA(final A a)
{
  a.setName("foo");
}

handleA(new B());

So what i'm saying is that B is still valid in the context of code using A.

marsouf
  • 1,107
  • 8
  • 15
  • 1
    I guess it's restricted because of the complexities it will add with method resolution when there are also overloaded methods with similar signatures. – Codebender May 02 '18 at 12:22

1 Answers1

1

Because CharSequence is not only a String, while a String is a CharSequence. In other words CharSequence can also be CharBuffer, Segment, String, StringBuffer, StringBuilder.

That's why you can not change the parameter type of setName(String) to CharSequence.

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107