educative.io

Please Give an Example of Annotation in Class Diagram

Give a sample class diagram and sample annotations in java.


Course: Grokking the Low Level Design Interview Using OOD Principles - Learn Interactively
Lesson: Class Diagram

Hi @varun_joshi

I hope everything is going well with you. Thank you for reaching out about this.

Below is a sample class diagram, along with the corresponding Java code, demonstrating the use of annotations in Java:

Class Diagram:

image

Java code:

public class BankAccount {
    private String accountNumber;
    private double balance;

    @Deprecated
    public BankAccount(String accountNumber) {
        this.accountNumber = accountNumber;
        this.balance = 0.0;
    }

    @SuppressWarnings("unused")
    public void deposit(double amount) {
        balance += amount;
    }

    @SuppressWarnings({"unused", "unchecked"})
    public void withdraw(double amount) {
        if (balance >= amount) {
            balance -= amount;
        } else {
            System.out.println("Insufficient funds");
        }
    }

    public double getBalance() {
        return balance;
    }
}

public class Customer {
    private String name;
    private String address;

    @Override
    public String toString() {
        return "Customer [name=" + name + ", address=" + address + "]";
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount account = new BankAccount("12345");
        account.deposit(100.0);
        System.out.println("Balance: " + account.getBalance());

        Customer customer = new Customer("John Doe", "123 Main St");
        System.out.println(customer);
    }
}

This example includes annotations such as @Deprecated , @SuppressWarnings , and @Override to demonstrate their usage in Java. The @Deprecated annotation marks the constructor as deprecated, @SuppressWarnings suppresses warnings for unused methods, and @Override indicates that a method is overriding a superclass method.

I hope that this guide is helpful. Remember that I am always available via message to help you with any difficulty you might encounter.

Regards,
Happy Learning :slight_smile: