Two interfaces with the same method name, what happens when I override?
So, I have a class "MyClass" and two interfaces "A" and "B"
public class MyClass implements A, B {
@Override
public void mymethod(){
System.out.println("hello world");
}
}
...
public interface A {
void mymethod();
}
...
public interface B {
void mymethod();
}
Which method from which interface is being overridden here?
I think both?
Thank you (Student)
source to share
In this case, it will only look like one method. In this case, it overrides "both" methods because they have the same signature. If the methods had different signatures (return type or whatever) then there would be a problem. Check this answer here
Example:
public class MyClass implements A, B {
@Override
public void mymethod(){
System.out.println("hello world");
}
}
...
public interface A {
void mymethod();
}
...
public interface B {
String mymethod();
}
This will cause a problem ...
source to share
((A)(new MyClass())).mymethod();
((B)(new MyClass())).mymethod();
outputs
hello world
hello world
Just check what it can .
If you run into this, there is potentially some kind of common function between A and B that could be abstracted from another interface that extends A and B, or unwanted common terminology occurs between them causing overlap and something might need to be renamed ...
source to share
An interface is just a contract.
Implementation A means MyClass
must have a method void mymethod()
.
B's value implementation MyClass
must have a method void mymethod()
.
It overrides both, but I'm not sure if this is the correct way to say it.
It's just about filling out the contract and making sure MyClass has the correct method.
source to share