开发者

Doubt in Java interface implements

开发者 https://www.devze.com 2023-04-07 19:54 出处:网络
interface Device { public void doIt(); } public class Electronic implements Device { public void doIt() { } } abstract class Phone1 extends Electronic
interface Device
{
  public void doIt();
}

public class Electronic implements Device
{
   public void doIt()
   {
   }
}

abstract class Phone1 extends Electronic
{
}
abstract class Phone2 extends Electronic
{
   public void doIt(int x)
   {
    }
}

class Phone3 extends Electronic implements Device
{   
    public void doStuff()
    {
开发者_运维知识库     }
}

Can any one tell me why this compiles.. Because "Phone3" implements Device and it should have doIt() method but it does not have. But still this compiles. May i know Y?


Phone3 extends Electronic, and Electronic has the method doIt(), implementing the Device interface. The implementation of the doIt method is thus just inherited from the Electronic base class.

It makes sense if you make the example more realistic. Change Device to Ringable, with a ring method. Create a base class SimplePhone implementing Ringable, with an implementation of the ring method. And make a subclass of SimplePhone called BeautifulPinkPhone. The beautiful pink phone will be able to ring because it's just a simple phone with a pink color.


implements Device is redundant in class Phone3 definition. The class in inheriting the fact of implementing the Device interface from the Electronic class.

That is, every class extending Electronic is implementing Device also, and is also inheriting the implementation of doIt that Electronic provides. Every one of them can extend/provide a different implementation of doIt by overriding it.


It is because Phone3 extends Electronic and Electronic already implements doIt() method.


it works, because Electronic implements Device. have you tried compiling without interface implementation in main class?


Phone3 inherits it from the Electronic class.


Phone3 extends Electronic and inherits all it's methods. Since Electronic has a doIt() method it compiles.


Phone3 extends Electronic hence it inherits doIt() method


If you see in a above code, Phone3 already implemented doIt() method in a inheritance tree,i.e in a Electronic class, and if you wish to call doIt() method in your Phone3 class it'll work fine such as.

class Phone3 extends Electronic implements Device
{   
public void doStuff()
{

}
public static void main(String...args)
{
    Phone3 p3=new Phone3();
    p3.doIt();
}
}


Phone3 extends Electronic, which already implements doIt.


Cause Phone3 also extends Electronic which has a empty implementation for the doIt method.
So it does not need to have it, unless it needs to override the behaviour.

0

精彩评论

暂无评论...
验证码 换一张
取 消