Vikram Darsi
Vikram Darsi

Reputation: 89

Add new method to an interface which is directly implemented by many classes

I have a small question on java interfaces

Is there any way to add a new method to java interface without modifying the classes that are implementing it.

condition is that I should not introduce new interface

Upvotes: 5

Views: 2984

Answers (3)

Arul Antony
Arul Antony

Reputation: 1

By using abstract class we can solve this problem.

   interface A{
     void a();
     void b();
    }

  Class a implement A 

  Class b implement A ...

if any new method arrive to create an abstract class and add that method into it

 abstract class adapter { 
       abstract void c();
     }

now extend this adapter class for necessary classes..

Upvotes: 0

Tim B
Tim B

Reputation: 41178

What you are trying to do is fundamentally impossible. Unless (as was just pointed out in the comments) you use Java 8.

Java 8 has introduced a concept of default or defender methods that allow you to add a method to an interface and provide a default implementation of that method within the interface.

http://zeroturnaround.com/rebellabs/java-8-explained-default-methods/

The rest of the answer applies to any version of Java before 8:

An interface describes the methods in a class. If you add a new method to an interface then all classes that implement the interface must implement the method. Unless by some stroke of luck the method you are adding already exists in every single implementing class this is just impossible without either adding a new interface or changing the classes.

If your interface were an Abstract Class then you could add a stub method that does nothing and allow that to be overridden but interfaces have no concept of optional methods.

Upvotes: 2

user207421
user207421

Reputation: 310885

Is there any way to add a new method to java interface without modifying the classes that are implementing it.

No.

condition is that I should not introduce new interface

If the condition also includes not modifying the many classes that directly implement the interface, you have been given an impossible task.

This is the reason why interfaces are often accompanied by abstract Adapter classes, that implement all the methods in a do-nothing way. Implementation classes then extend the adapter rather than implementing the interface, so that if you need to add an interface you only need to modify the interface and the adapter.

Upvotes: 8

Related Questions