Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method overriding, subclass taking a super type of the parameter type [duplicate]

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.

like image 881
marsouf Avatar asked Dec 18 '25 22:12

marsouf


1 Answers

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.

like image 82
Murat Karagöz Avatar answered Dec 21 '25 11:12

Murat Karagöz