I have two contracts (interfaces) both have default method with same name but different return type.
I have to create a Class which should implement both the contract. If I am trying to do it then it is giving me the compilation error.
I can't change the default method of Cotract1 as many classes are implementing Contract1 and the same with Contract2.
Is there anyway by which I can write the class which should have the implementation of both the interfaces, without changing anything in the interface.
Below is the piece of code:
interface Contract1 {
default String getVersion() {
return "Beta_10.2.3";
}
//....
}
interface Contract2 {
default Double getVersion() {
return 11.2;
}
//....
}
public class ContractsImplementation implements Contract1, Contract2{
}
Suggestion:
Sanjay, if you do not want to have any default methods in your class like you said, use composition over inheritance.
interface Contract1 {
default String getVersion() {
return "Beta_10.2.3";
}
//....
}
interface Contract2 {
default Double getVersion() {
return 11.2;
}
//....
}
public class ContractsImp {
private class Contract1Imp implements Contract1 {}
private class Contract2Imp implements Contract2 {}
private Contract1 contract1 = new Contract1Imp();
private Contract2 contract2 = new Contract2Imp();
// Here you can do with contracts whatever you want
// ...
}
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