SDA LabSession3
SDA LabSession3
Exercise
1. Write a class representing a user profile. Ensure that it adheres to the SRP by having
only one responsibility. Separate concerns such as data storage, authentication, and
profile information display into different classes.
CODE:
class UserProfile {
String name;
String address;
String contact;
String NIC;
String emailAddress;
String qualifications;
public UserProfile() {
this.name = name;
this.contact= contact;
this.NIC = NIC;
this.emailAddress = emailAddress;
this.qualifications = qualifications;
this.address = address;
}
// AuthenticationManager.java
public class AuthenticationManager {
public boolean authenticateUser(String username, String password) {
// Implementation details for user authentication
return false;
}
}
// ProfileDisplay.java
public class ProfileDisplay {
public void displayUserProfile(UserProfile user) {
// Implementation details for displaying user profile information
}
}
}
}
2. Implement a basic shape hierarchy (e.g., Circle, Square, and Triangle). Extend this
hierarchy to support the calculation of area for each shape without modifying the
existing shape classes.
CODE:
abstract class Shape {
public abstract double calculateArea();
}
class Rectangle extends Shape {
protected double width;
protected double height;
@Override
public double calculateArea() {
return width * height;
}
}
@Override
public double calculateArea() {
return 3.14 * radius * radius;
}
}
class Square extends Shape {
private double side;
@Override
public double calculateArea() {
return side * side;
}
}
class ShapeHierarchy{
public static void main(String[] args){
Square obj1= new Square();
Rectangle obj2=new Rectangle();
Circle obj3=new Circle();
obj1.setSide(5);
obj2.setWidth(4);
obj2.setHeight(3);
obj3.setRadius(3);
System.out.println("Square Area: "+obj1.calculateArea());
System.out.println("Rectangle Area: "+obj2.calculateArea());
System.out.println("Circle Area: "+obj3.calculateArea());
}
}
3. Create an interface representing a shape and two classes implementing this interface:
Rectangle and Square. Ensure that the Square class can be substituted for the Rectangle
class without altering the behavior of the program.
CODE:
@Override
public double area() {
return width * height;
}
}
4. Define an interface for a document printer. Implement classes for different types of
printers (e.g., InkjetPrinter, LaserPrinter). Ensure that each printer class implements only
the methods relevant to its type.
CODE:
// Example usage
public class PrinterDemo {
public static void main(String[] args) {
DocumentPrinter inkjet = new InkjetPrinter();
DocumentPrinter laser = new LaserPrinter();
inkjet.print(myDocument);
laser.print(myDocument);
}
}
CODE:
interface IMessageSender {
void sendMessage(String recipient, String message);
}
class NotificationService {
private final IMessageSender messageSender;