LearnFrenzy
Sign in Take a free test

Inheritance · Inheritance Programs · Question 5

Notification channels sharing a send template in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

Write a Notification superclass whose final send() validates the recipient, formats the message and records it, while EmailNotification and SmsNotification supply their own validation and format.

Solution
Main.java
import java.util.ArrayList;
import java.util.List;

abstract class Notification {
    static final List<String> SENT = new ArrayList<>();

    final String send(String to, String msg) {
        if (!valid(to)) return "invalid recipient: " + to;
        String out = format(to, msg);
        SENT.add(out);
        return out;
    }

    protected abstract boolean valid(String to);
    protected abstract String format(String to, String msg);
}

class EmailNotification extends Notification {
    @Override protected boolean valid(String to) { return to.matches("[^@\\s]+@[^@\\s]+\\.[a-z]+"); }
    @Override protected String format(String to, String msg) { return "EMAIL to " + to + " | Subject: " + msg.split("\\.")[0]; }
}

class SmsNotification extends Notification {
    @Override protected boolean valid(String to) { return to.matches("[6-9]\\d{9}"); }
    @Override protected String format(String to, String msg) {
        String text = msg.length() > 20 ? msg.substring(0, 17) + "..." : msg;
        return "SMS to " + to + " | " + text;
    }
}

public class Main {
    public static void main(String[] args) {
        Notification email = new EmailNotification(), sms = new SmsNotification();
        String msg = "Your order has shipped. Track it in the app.";
        System.out.println(email.send("asha@mail.com", msg));
        System.out.println(email.send("asha.mail.com", msg));
        System.out.println(sms.send("9876543210", msg));
        System.out.println(sms.send("12345", msg));
        System.out.println(Notification.SENT.size() + " sent");
    }
}

Output Verified by compiling and running

EMAIL to asha@mail.com | Subject: Your order has shipped
invalid recipient: asha.mail.com
SMS to 9876543210 | Your order has sh...
invalid recipient: 12345
2 sent

The parent fixes the steps of sending (the Template Method pattern); each subclass fills in only what differs.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links