Same method in Interface and Abstract class
I came to situation :
public interface Intr {
public void m1();
}
public abstract class Abs {
public void m1() {
System.out.println("Abs.m1()");
}
// public abstract void m1();
}
public class A extends Abs implements Intr {
@Override
public void m1() {
// which method am I overriding, well it is Abs.m1() but why?
// if method implemented is Abs.m1(), then why I am not getting error for Intr.m1() not implemented.
}
}
You are satisfying both conditions at once; ie. the one implementation is at the same time fulfilling the abstract class requirements and the interface requirements.
As a note, unless you are using Intr
in another inheritance chain, you don't need it. Also, it might make sense to move the implements Intr
up to the abstract class definition.
You can only override methods defined in another class.
Methods declared in an interface are merely implemented. This distinction exists in Java to tackle the problem of multiple inheritance. A class can only extend one parent class, therefore any calls to super
will be resolved without ambiguity. Classes however can implement several interfaces, which can all declare the same method. It's best to think of interfaces as a list of "must have"s: to qualify as a Comparable
your cluss must have a compareTo()
method but it doesn't matter where it came from or what other interfaces require that same method.
So technically you override Abs.m1()
and implement Intr.m1()
in one fell swoop.
Note that this would be fine too:
public class B extends Abs implements Intr {
//m1() is inherited from Abs, so there's no need to override it to satisfy the interface
}
Here, both the interface and abstract class have the same method.
You have one class with named Derived
which extends an abstract
class and implement
an interface. It's true and you override print method on Derived
class it's fine and it compiles correctly and does not give any error but here you can't identify which class method is overridden like abstract class or interface.
This is runtime polymorphism you can't create an instance of an abstract class or interface but you can create a reference variable of that type. Here the solution is you can't identify that on compile-time it's actually overridden at run time.
interface AnInterface
{
public void print();
}
abstract class Base
{
public abstract void print();
}
public class Derived extends Base implements AnInterface
{
public void print(){
System.out.println("hello");
}
AnInterface iRef = new Derived();
iRef.print(); // It means interface method is overridden and it's decided when we call the method.
Base base = new Derived();
base.print(); // It means abstract class method is overridden.
}