Interface Inheritance - Change Method Parameters

I am having difficulty understanding the java method for interpreting interface inheritance, for example:

public interface Model { Model getModel(); void setModel(Model model); } public class BaseModel implements Model { @Override public BaseModel getModel() { return null; } // works @Override public void setModel(BaseModel model) {} // compilation error, it wants Model instead of BaseModel } 

Can someone explain why the first method works and the second does not?

+6
source share
4 answers

To understand this, you must ask yourself: "Can I fine tune BaseModel for any use of the Model interface?

When you specialize in return value, this works just fine. Even if getModel() returns a BaseModel , it can always be assigned to the Model variable.

 Model model = myModel.getModel(); 

Otherwise, this is not true:

 SomeOtherModel other = ...; myModel.setModel(other); // no problem myBaseModel.setModel(other); // other is not a BaseModel! 

if setModel was to accept the BaseModel parameter, you would break its ability to be set with other implementations of the Model . Therefore, this is not permitted.

+3
source

Your first type of return method is covariant and allowed, and the return type is not part of the method signature, so its allowed

So far, the parameter to the method is part of the signature and must strictly follow the interface signature and, therefore, it fails in your case.

Now that you have annotated your method with @Override , you are trying to override the method, so the compiler complains about the same thing. If you simply delete this and implement the method in accordance with the interface in addition to the existing implementation, you will overload this method.

+5
source

How the function override function works.

  • Function parameters must be exactly identical.

  • The types of data returned may be different, but must be related.

So, in your case, getModel excellent, since the return type ( BaseModel ) is associated with the Model , but setModel not valid, since the parameter types are different from each other.

+3
source

The method name and parameter types sign the method in Java, not the return type. When you redefine a method, the signature of the method must be the same. If you change the signature, it will be overloaded, and not redefined - to see it, if you delete the @Override annotation, it will work.

+2
source

Source: https://habr.com/ru/post/979311/


All Articles