Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doubt in Java interface implements

Tags:

java

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?

like image 968
sai sindhu Avatar asked Jul 19 '26 09:07

sai sindhu


2 Answers

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.

like image 188
JB Nizet Avatar answered Jul 21 '26 22:07

JB Nizet


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.

like image 25
Xavi López Avatar answered Jul 21 '26 23:07

Xavi López