Java multiple interface ambiguity


I've been told in lectures that the reason why Java doesn't support multiple inheritance is because every class inherits from the Object class which negates the need for it (perhaps), and because it prevents problems encountered in languages like C++ where multiple parent classes might have methods and data members with the same signatures and names.

What Java does support though is multiple interfaces which lends objects consistent behaviour even if they're completely different:

public class Bicycle implements PeddlePower, Purchasable {
   // I want to ride my bicycle,
   // I want to ride my bike…
public class Keyboard implements Purchasable {
   // Bucking spring keyboards are the shiz

What I wanted to know is whether or not different interfaces with the same abstract methods and data members could cause a similar clash to the ones avoided by not having multiple inheritance, or whether it would cause an override.

public interface InterfaceA { final int x = 4; }
public interface InterfaceB { final int x = 4; }
public class Testing implements InterfaceA, InterfaceB {
   public class Testing {

Turns out it does generate an error, and now that I've seen it, it does make sense. reference to x is ambiguous, 
both variable x in A and variable x in B match

My reasoning was: imagine you're passing the Testing object to a setter method that accepts any object that implements InterfaceA. I assumed it would know to use the int x data member from InterfaceA and NOT from InterfaceB right? Well of course not, just because it's been passed through something that only accepts objects that implement InterfaceA, that doesn't mean it's lost it's InterfaceB!

Anyway to seasoned Java folk this probably all seems childish and silly, but I find if I try to explain a logic problem out loud to somebody, often I learn the answer myself in the process; in this case why two interfaces can't have methods and data members with the same signatures and names after all! Well technically they could provided you're sure both interfaces will never be used on the same objects at the same time.

Author bio and support


Ruben Schade is a technical writer and infrastructure architect in Sydney, Australia who refers to himself in the third person. Hi!

The site is powered by Hugo, FreeBSD, and OpenZFS on OrionVM, everyone’s favourite bespoke cloud infrastructure provider.

If you found this post helpful or entertaining, you can shout me a coffee or send a comment. Thanks ☺️.