Alert Channel with Interface
A school control room can send a short alert in two ways: by email or by SMS. The final message format depends on the chosen channel, but the message text itself is the same.
Your task is to model this with an interface. If the channel is "email", return "EMAIL: message". If the channel is "sms", return "SMS: message".
For example, if the input is "email" and "Gate opens at 7", the result should be "EMAIL: Gate opens at 7". If the input is "sms" and "Bus delayed", the result should be "SMS: Bus delayed".
You may assume the input channel is always either "email" or "sms". The point of the challenge is to use an interface so different classes can provide the same method in their own way.
Example Input & Output
The same interface method works for any message text.
The SMS implementation uses its own prefix with the same send method.
The email implementation adds the EMAIL prefix.
Algorithm Flow

Solution Approach
This problem is a simple introduction to interfaces and polymorphism in Java. Both alert channels perform the same kind of action, but they produce slightly different outputs. That is exactly the sort of situation where an interface works well.
You can define an interface like AlertChannel with one method, for example send(). Then create two classes, such as EmailAlert and SmsAlert, that both implement that interface.
The common shape looks like this:
Each concrete class stores the message text and returns its own channel-specific prefix. One adds EMAIL:, the other adds SMS:.
Then the solution method can choose which implementation to create based on the input channel string. After that, it does not need to care which specific class it is holding. It can work through the interface type and just call send(). That is the key interface lesson: one shared contract, multiple concrete implementations.
This is still an easy problem because the logic itself is small. But it introduces a very important object-oriented idea. The calling code depends on the interface, while the actual implementation can vary behind it.
The runtime is O(1), and the main value of the exercise is learning how interfaces let Java code stay flexible and organized even for very small behaviors.
Best Answers
interface AlertChannel {
String send();
}
class EmailAlert implements AlertChannel {
private String message;
public EmailAlert(String message) {
this.message = message;
}
public String send() {
return String.format("EMAIL: %s", message);
}
}
class SmsAlert implements AlertChannel {
private String message;
public SmsAlert(String message) {
this.message = message;
}
public String send() {
return String.format("SMS: %s", message);
}
}
class Solution {
public static String sendAlert(String channel, String message) {
AlertChannel alert = channel.equals("email") ? new EmailAlert(message) : new SmsAlert(message);
return alert.send();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
