Reputation: 215
Let's say I have an Interface called Parent
interface Parent{
void methodOne();
}
This interface gets implemented in 10 different Child classes let's say
class Child1 implements Parent{
void methodOne();
}
class Child2 implements Parent{
void methodOne();
}
:
:
class Child10 implements Parent{
void methodOne();
}
How do we add new method to Parent interface and not break other 10 classes.
interface Parent{
void methodOne();
void methodtwo();
}
I know in Java 8 we can add default methods but is there any other way prior to Java 8 to do that
Upvotes: 0
Views: 42
Reputation: 333
Default methods were introduced because if you were to add a new method to an interface, then all the classes implementing this interface would throw errors by forcing you to implement the new method inside them, which is what breaking of classes means, but if you add any new method to an interface, the method must be implemented by all the classes that implement the interface if the method is not declared as default. As you have noted, this was introduced in Java 8 to help in achieving backward compatibility. For further clarification about this, you can check this article. You can also check this almost similar question to guide you from the answers given. However, for previous Java versions, you can use Abstract class instead of interfaces to avoid breaking of classes.
Upvotes: 2
Reputation: 57346
Without default implementations you can't add methods to interfaces without having to implement it in each of the implementing classes. The way around it is to have your classes extend an abstract class, which in turns implements the interface. You'd have something like this:
public interface Parent {
public void methodOne();
}
public abstract class AbstractChild implements Parent {
//literally, leave blank
}
public class Child1 extends AbstractChild {
public void methodOne() {
//implementation goes here
}
}
....
Now if you want to add new methods to the interface, you can implement them in your AbstractChild
- and all ChildX
classes would not need to be touched.
Upvotes: 2