1. Interfaces in Java
Welcome back! When working with OOP in Java, there are times when we want to be selective about which methods a class inherits. However, inheritance by design can lead to subclasses inheriting properties they don't use, as all public methods are inherited.
2. Limitations of inheritance
Consider our Car class. If we add a property like batteryCapacity to support electric cars, a class for Toyota will inherit this property but may not use it as most Toyota cars are not electric cars.
3. Creating interfaces
Interfaces become helpful when selective inheritance is needed. They allow us to provide properties and methods only where they are relevant. For example, we can use an interface to make our Tesla class inherit specific properties that are only applicable to electric cars.
To create an interface, we use the keyword interface in place of the class keyword. In order to use the interface in a class, you can use the implements keyword after the class name and then provide the interface name. Once a class has implemented an interface, all methods inside the interface must be implemented in the class.
4. Adding properties to interfaces
We add the BATTERY_CAPACITY property inside the interface declaration and provide a value of 310 for the range in miles. In Java, it is a good convention to name interface properties using an uppercase snake-case naming convention that requires the property's name to be written in uppercase with an underscore to separate words for better readability. We must also provide a value when we create an interface property because all interface properties are implicitly set to be public, static, and final. Final is a new keyword used to ensure the values of properties cannot be changed once set. Using the upper snake case convention in Java also signifies that the property is a constant and that its values cannot be changed. To access the BATTERY_CAPACITY property, we can call it directly from within the Tesla class without needing the this keyword, as we would typically do for other class properties.
5. Adding interface methods
Interfaces are typically used to declare methods that classes will implement. For example, our ElectricCar interface can specify a void charge method, which the Tesla class would implement. While interfaces can have concrete methods, they usually contain abstract methods. Once a class has implemented an interface, all abstract methods inside the interface must be implemented in the class.
6. Let's practice!
When working with interfaces, use the "has-a" phrase to determine if an interface is appropriate. For instance, a Tesla has a charger, which suggests it should implement the ElectricCar interface. Whenever you find yourself using "has-a," consider creating an interface. Now, it's your turn to create some interfaces for your classes!