i tried doing this :
interface pet {
void sleep();
}
interface robot {
void sleep();
}
public class roboGarfield implements pet , robot {
/*
* this gives error
void pet.sleep(){
}
*/
@Override
public void sleep() { System.out.println("this isn't really specific.."); }
public static void main(String[] args){
roboGarfield t = new roboGarfield();
t.sleep();
((pet)t).sleep(); // similar to C#
((robot)t).sleep();
}
}
But even though i can cast the roboGarfeild
object to its pet
or robot
type , i cant do an explicit implementation like c#.
Anything i'm doing wrong ? or is it just not supported in java ?
Edit: So , java doesn't support explicit interface implementation like C#. But for cases where they can't be avoided , Holger's delegate method seems like the way out.
Thanks for all the replies.
The standard solution to this kind of problem is to use delegation:
interface pet {
void sleep();
}
interface robot {
void sleep();
}
public class roboGarfield {
private final pet myPetIdentity = new pet() {
public void sleep() { System.out.println("sleeping as pet"); }
public String toString() { return roboGarfield.this.toString(); };
};
private final robot myRobotIdentity = new robot() {
public void sleep() { System.out.println("recharging as robot"); }
public String toString() { return roboGarfield.this.toString(); };
};
public final pet asPet() {
return myPetIdentity;
}
public final robot asRobot() {
return myRobotIdentity;
}
public static void main(String[] args){
roboGarfield t = new roboGarfield();
t.asPet().sleep();
t.asRobot().sleep();
}
}
For bigger methods it’s recommended to let the inner classes delegate back to the outer class to keep the inner classes short. Further, subclasses could override these methods without dealing with the delegation stuff then.
public class roboGarfield {
private final pet myPetIdentity = new pet() {
public void sleep() { petSleep(); }
public String toString() { return roboGarfield.this.toString(); };
};
private final robot myRobotIdentity = new robot() {
public void sleep() { roboSleep(); }
public String toString() { return roboGarfield.this.toString(); };
};
public void roboSleep()
{
System.out.println("recharging as robot");
}
public void petSleep()
{
System.out.println("sleeping as pet");
}
public final pet asPet() {
return myPetIdentity;
}
public final robot asRobot() {
return myRobotIdentity;
}
public static void main(String[] args){
roboGarfield t = new roboGarfield();
t.asPet().sleep();
t.asRobot().sleep();
}
}
Java does not do that.
If two interfaces define methods of identical signature, there is no way to distinguish between them and you can only provide a single implementation that will be used by both.
You have to take care not to end up with interfaces that are incompatible that way.
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