Before moving on, here are a couple things to keep in mind with interfaces:
It's not required, but a common convention is to prefix interface names with the letter "I" to indicate it's an interface. This helps developers quickly realize that the type they see is an interface. So instead of Customer
let's refer to the interface from here on out as ICustomer
.
Another common convention is for the concrete class to have the name of the interface postfixed. That's why we named the class B2B_Customer
and B2C_Customer
instead of B2B
and B2C
.
Interfaces are not classes. You can't instantiate them:
ICustomer c = new ICustomer();
Will cause a compilation error: Type cannot be constructed: ICustomer
.
You can not declare variables inside an interface:
public interface ICustomer { String customerName = ''; // Not allowed Boolean isEligibleForDiscount(); void sendNotification(String message); }
Unfortunately, this causes compilation errors that are really unclear like Expecting '(' but was: '='
.
Interface methods have no access modifiers. They’re always global.
public interface ICustomer { public Boolean isEligibleForDiscount(); // Can't declare this as public private void sendNotification(String message); // Can't declare this as private either }
The access modifiers here are not allowed. It'll cause a compilation error with another unclear and indirect error: Expecting '}' but was: 'public'
. However, the interface declaration itself can be either public or global.
The concrete implementation of the abstract methods must also be public or global.
public class B2B_Customer implements ICustomer { public Boolean isEligibleForDiscount(){ Boolean isEligible = false; // logic for determining discount return isEligible; } private void sendNotification(String message){ // Can't declare this as private // logic for sending a notification } }
Will cause a compilation error: B2B_Customer: Overriding implementations of global or public interface methods must be global or public: void Customer.sendNotification(String)