Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does all the interface methods need to be implemented in a class implementing it in java

Tags:

java

interface

I know that it is the purpose of the interface and the class can be declared abstract to escape from it.

But is there any use for implementing all the methods that we declare in an interface? will that not increase the weight and complexity of the code if we keep on defining all the methods even it is not relevant for that class? why it is designed so?

like image 259
Deepak Avatar asked Aug 25 '12 11:08

Deepak


People also ask

Why do you need to implement all the methods of an interface in class which implements an interface?

It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and are public and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface.

Do we need to implement all the methods of an interface in a class?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class.

What will happen if we are not implementing all the methods of an interface in class which implement an interface?

If you don't implement all methods of your interface, than you destroy the entire purpose of an interface.

What is the purpose of writing an interface before implementing a class?

Implementing an interface allows a class to become more formal about the behavior it promises to provide. Interfaces form a contract between the class and the outside world, and this contract is enforced at build time by the compiler.


1 Answers

The idea of an interface in Java is very much like a contract (and perhaps seen in retrospect this should have been the name of the concept)

The idea is that the class implementing the interface solemnly promises to provide all the things listed in the contract so that any use of a class implementing the interface is guaranteed to have that functionality available.

In my experience this facility is one of the things that makes it possible to build cathedrals in Java.

like image 177
Thorbjørn Ravn Andersen Avatar answered Nov 15 '22 18:11

Thorbjørn Ravn Andersen