I have difficulties understanding the java way of interpreting interface inheritance, 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
}
Could anyone explain why the first method works, and the second doesn't?
Yes, you can have overloaded methods (methods with the same name different parameters) in an interface. You can implement this interface and achieve method overloading through its methods.
Static methods in interfaces are never inherited.
If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface. In short, you can access the default methods of an interface using the objects of the implementing classes.
No. Interface methods can be implemented. To overload/override a method, that method must be defined first.
In this article, we will understand how the concept of inheritance is used in the interface. An interface is a set of specifications or statements that define what a class can do without specifying how the class will do it. The interface is always abstract. A concrete class must implement all the abstract methods specified in the interface.
This example illustrates the important point that interfaces are lightweight contract entities, and client code must provide the contents; in other words, the method code. It's perhaps a little surprising that C# interfaces can also be treated as parameters, as shown in Listing 3.
In the interface inheritance, the static methods are not changed throughout the execution and they are not inherited. Hence, they cannot be overridden.
Like a class, an interface can have methods and variables, but the methods declared in an interface are by default abstract (only method signature, no body). In this article, we will understand how the concept of inheritance is used in the interface.
In order to understand this, you should ask yourself "can I substitude BaseModel
for any usage of the Model
interface"?
When you specialize the return value, this works fine. Even if getModel()
returns a BaseModel
, it can always be assigned to a Model
variable.
Model model = myModel.getModel();
The other way round is not true, however:
SomeOtherModel other = ...;
myModel.setModel(other); // no problem
myBaseModel.setModel(other); // other is not a BaseModel!
if setModel
were to accept a BaseModel
parameter you'd break its ability to be set with other implementations of Model
. Hence, this is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With