Skip to main content

Visibility symbols +, -, # in classes

Short answer

UML visibility signs (+ public, - private, # protected, ~ package) enforce encapsulation by controlling member access. In Java, private members are class-only, protected allows subclass and package access, public is universal. Example: Account has private balance, protected accountNo, public deposit/getBalance, protected audit; subclass can access accountNo and audit but not balance.

You will find - (minus signs), + (plus signs), # (hash marks) in front of operation names and attributes in UML class diagrams. Why they are used for? With the help of any one of the object oriented programming language syntax implement the different semantics of +, -, # sign used in implementation of Object Oriented System.

Why the signs are used

In a UML class diagram the symbols in front of an attribute or operation show its visibility (access level): who is allowed to use that member.

SignVisibilityMeaning
+publicAccessible from any class
-privateAccessible only inside the same class
#protectedAccessible in the class and its subclasses (and the package in Java)
~packageAccessible in the same package

They support encapsulation: data is kept hidden (-), and only the operations that form the class interface are public (+).

 +----------------------+
 |       Account        |
 |----------------------|
 | - balance : double   |
 | # accountNo : String |
 |----------------------|
 | + deposit(amt)       |
 | + getBalance()       |
 | # audit()            |
 +----------------------+

Implementation in Java

class Account {
    private double balance;          // - : only Account
    protected String accountNo;      // # : Account, subclasses, package
    public void deposit(double amt) { // + : everyone
        balance += amt;
        audit();
    }
    public double getBalance() { return balance; }
    protected void audit() { System.out.println("audit " + accountNo); }
}

class SavingAccount extends Account {
    void test() {
        accountNo = "S1";           // OK  : protected is inherited
        audit();                    // OK
        // balance = 5;             // ERROR: private to Account
    }
}

class Main {
    public static void main(String[] a) {
        Account acc = new Account();
        acc.deposit(500);                 // OK  : public
        System.out.println(acc.getBalance());
        // acc.balance = 1000000;         // ERROR: private
        // acc.audit();  // not allowed from a different package
    }
}

Semantics shown: + members are the interface of the object, - members are hidden implementation, and # members are available only to subclasses and package classes so that inheritance can extend the class without exposing it to everybody.

All Object Oriented Analysis and Design chapter 3 questions →