Complete the code to declare a class that follows the Open/Closed Principle by allowing extension without modification.
class Shape { public void draw() { // base draw method } } class Circle extends Shape { @Override public void [1]() { System.out.println("Drawing Circle"); } }
The subclass overrides the draw method to extend behavior without modifying the base class, following the Open/Closed Principle.
Complete the code to add a new shape class without modifying existing classes, adhering to the Open/Closed Principle.
interface Shape {
void draw();
}
class Rectangle implements Shape {
public void draw() {
System.out.println("Drawing Rectangle");
}
}
class [1] implements Shape {
public void draw() {
System.out.println("Drawing Triangle");
}
}Adding a new Triangle class that implements the Shape interface extends functionality without changing existing code, following the Open/Closed Principle.
Fix the error in the code to ensure the Open/Closed Principle is not violated when adding new payment methods.
abstract class Payment { abstract void pay(); } class CreditCardPayment extends Payment { void pay() { System.out.println("Paying with Credit Card"); } } class PaymentProcessor { public void processPayment(Payment payment) { payment.[1](); } }
The processPayment method calls the abstract pay method, allowing new payment types to be added without modifying this method, thus respecting the Open/Closed Principle.
Fill both blanks to implement a notification system that follows the Open/Closed Principle by supporting multiple notification types.
interface Notification {
void send();
}
class EmailNotification implements Notification {
public void [1]() {
System.out.println("Sending Email");
}
}
class NotificationService {
public void notifyUser(Notification notification) {
notification.[2]();
}
}Both blanks use the send method to ensure the system can be extended with new notification types without modifying existing code, following the Open/Closed Principle.
Fill all three blanks to implement a logging system that adheres to the Open/Closed Principle by allowing new loggers without modifying existing code.
interface Logger {
void [1](String message);
}
class ConsoleLogger implements Logger {
public void [2](String message) {
System.out.println("Console: " + message);
}
}
class LoggerService {
public void logMessage(Logger logger, String message) {
logger.[3](message);
}
}The method log is consistently used in the interface, implementation, and service to allow extension without modification, following the Open/Closed Principle.