Using Default Interfaces to create Protocols
Protocol Oriented programming is a newer paradigm which was made popular by Swift. The idea behind it is to focus on the functionality of an object (what it can do and its behaviors) instead of the classic OOP focus of what an object is.
We can do something very similar to what Swift does with protocols in Java by leveraging default methods. In Java, we have interfaces and abstract classes. Interfaces are great because we define a schema of functions every class must implement (but we can’t implement methods in the interface itself) and abstract classes are great because they do let us implement some of these methods if we choose (however our subclasses can only extend one abstract class).
There is a relatively unknown keyword introduced in Java 8 called default. With the default keyword, we can implement some of the methods in the interface itself, saving us from having to duplicate code if two or more implementing classes would implement the method the same way.
Below is an example of the new power we have with default methods.
Here are the two interfaces, as you can see they have both implemented and unimplemented methods.
And here are the implementing class, as you can see the Helicopter implements both interfaces and therefore must implement all of the methods.
We can then do something like this.
So there we have it, we have created protocols in java. This is a very cool paradigm that I will definitely be using to reduce code duplication across similar classes while at the same time allowing classes to be open to extension simply by declaring it implements another protocol.
There is one small difference between Swift and Java in that the interfaces cannot have instance variables (like the protocols in Swift can). We can get around this by creating the appropriate getters and setters in the interface to act like an instance variable (like I did for capacity and maxAltitude). Then, in the implementing class, you would have a variable for those values and return it or update when you override those getters and setters.