Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use extends and when to use interface?

We can extend a class but we cannot implement a class. We can implement an interface, but cannot extend an interface.

In what cases should we be using extends?

like image 655
pankajt Avatar asked Dec 07 '25 08:12

pankajt


1 Answers

extends is used for either extending a base class:

class ClassX extends ClassY {
    ...
}

or extending an interface:

interface InterfaceA extends InterfaceB {
    ...
}

Note that interfaces cannot implement other interfaces (most likely because they have no implementation).

Java doesn't impose any naming conventions for classes vs. interfaces (in contrast to IFoo for interfaces in the .NET world) and instead uses the difference between extends and implements to signify the difference to the programmer:

class ClassA extends ClassB implements InterfaceC, InterfaceD {
    ...
}

Here you can clearly see that you're building upon an existing implementation in ClassB and also implement the methods from two interfaces.

like image 175
Joey Avatar answered Dec 09 '25 20:12

Joey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!