Learn Java Programming - Interface: Default Methods Tutorial

Опубликовано: 12 Октябрь 2024
на канале: Daniel Ross
658
5

Prior to Java 8, the biggest issue with interfaces was a complete lack of scalability. Scalability allows an application to evolve and grow over time without breaking existing code. It is a concept that is learned mostly through experience. With a pre-Java 8 interface you had just about one chance to get your interface right and that was it. Once your interface was in production it became almost impossible to make a change or addition that didn't have major ripple effects.
In my Introduction to Interfaces tutorial I created two separate classes that implemented the same Engine interface, a Boeing787 and a Honda Accord. Let's suppose that I wanted to add a new abstract method called getHorsePower(), what would happen to the implementing classes? The next time I compiled both the 787 and the Accord classes, I would receive an error about an abstract method that I did not override. If I wanted to compile my code, and I do, I will have no choice but to override the new method. In the real world – if my interface was distributed and in production – I would have a bunch of very angry programmers knocking on my door.
The default method solves this issue and provides us with a new capability that did not exist before. Unlike an abstract method, a default method has a method body and it can execute statements and return values. A default method is similar to a regular class method only with the default keyword applied. I'm thinking that an interface is starting to look much more like an abstract class now ... interesting.