HI I have a question If interface has got four methods,and I like to implement only two methods, how this could be achieved?
Can any explain is that possible or should I go for implementing all the methods.
HI I have a question If interface has got four methods,and I like to implement only two methods, how this could be achieved?
Can any explain is that possible or should I go for implementing all the methods.
You can make the implementing class abstract
and implement two of the 4 methods from the interface.
It's not possible.
You can implement all four methods, but the two you don't need should throw an UnsupportedOperationException
.
If you control the design of the interface, simply split it in two. One interface specifies the two only some implementations implement, and one interface specifies the other two (or inherits the first two and adds more, your choice)
If you want a concrete class which is implementing this interface, then it is not possible to have unimplemented methods, but if you make have abstract class implementing this interface then you can leave any number of methods as you want to be unimplemented.
You can't "partially" implement an interface without declaring the implementing class abstract, thereby requiring that some subclass provide the remaining implementation. The reason for this is that an interface is a contract, and implementing it declares "I provide the behavior specified by the interface". Some other code is going to use your class via the declared interface and will expect the methods to be there.
If you know the use case does not use the other two methods you can implement them by throwing OperationNotSupported. Whether this is valid or not very much depends on the interface and the user. If the interface can legitimately be partially implemented this way it would be a code smell that the interface is poorly designed and perhaps should have been two interfaces.
You may also be able "implement" the interface by doing nothing, though this is usually only proper for "listener" or "callback" implementations.
In short, it all depends.
As other answers mention you cannot have a concrete class implementing only some of the methods of the interface it implements. If you have no control over the interface your class is extending, you can think of having Adapter classes. The abstract Adapter class can provide dummy implementation for the methods of an interface and the client classes can extend the Adapter class. (Of course the disadvantage is that you cannot extend more than one class)
This is common practice with GUI programming (using Swing) where the event listener class
might not be interested in implementing all methods specified by the EventListener interface. For example
take a look at the java.awt.event.MouseListener
interface and and the corresponding adapter class java.awt.event.MouseAdapter
.