interface A { public void m1(); }
**//Gives error**
class D implements A { public void m1(int x) { } }
**//this doen't**
abstract class G implements A { public void m1(int x) { } }
I have a doubt that why abstract class is able to override and class D can’t
If I see the second case
class X1
{
public void f2(){}
}
class X2 extends X1
{**//No error**
public void f2(int x){}
}
why public void m1() is not getting overidden in class D whereas same type of method f2() is getting overriden in class X2
In both cases we are overidding but why in interface case class D cant and in second case class X2 can override.
When there are two methods with the same name but different parameter types (or counts), that’s overloading, not overriding.
Ddoesn’t implementAitself because it doesn’t provide an implementation ofm1()– no parameters. It tries to provide a methodm1(int), but that doesn’t help to implement the interface – so it won’t compile (as it’s not an abstract class). It could provide both methods of course.X1provides a methodf2(), andX2extendsX1and adds a new overloadf2(int)– but it doesn’t override the method provided byX1.In particular, if you write:
Using the
@Overrideannotation makes all of this clearer:This now gives an error: