Showing posts with label Public. Show all posts
Showing posts with label Public. Show all posts

Tuesday, January 8, 2013

Access Modifiers | Private, Public & Protected


Access Modifiers | Private, Public & Protected

An access modifier determines the visibility of a class member (states & behaviours).



An access modifier of Public allows a class member to be accessed from external objects & is denoted on a class diagram with a + (addition) symbol.

A Private access modifier allows only internal access and prevents access by external objects. Private access is denoted on a class diagram with the - (minus) symbol.

The Protected access modifier allows internal access and access by child classes. Protected access is denoted on a class diagram with the # (hash) symbol.

Inheritance, Multiple Constructors & Abstract Classes


Inheritance

Classes contain state & behaviour - things they have & things they do. Just as humans inherit certain states & behaviours from their parents, so too can classes.


Figure 1: Basic inheritance class diagram.


Often referred to as a Parent-Child relationship. Other names include:

Parent | Superclass | Base class | Generalisation
Child | Subclass | Derived class | Specialisation

Consider the humble bank account. There may be many types of bank account but at their heart, is a single bank account type containing the basic state & behaviour common to all bank accounts.

Scenario: Bank accounts

There are two types of bank accounts - a savings account that attracts a 5% rate of interest on the balance and a credit card account that charges 20% interest on the balance. All bank accounts also have a number and may or may not have a minimum balance imposed on them.




Figure 2: Bank account package class diagram: BankAccount parent class & its child classes. Larger view

Figure 2 is a class diagram that models a simplified bank account package, using inheritance. It contains one parent class & two child classes. The parent contains all of the general state & behaviour for a bank account, the children contain specialised state & behaviour.




Access Modifiers | Private, Public & Protected

An access modifier determines the visibility of a class member (states & behaviours).

An access modifier of Public allows a class member to be accessed from external objects & is denoted on a class diagram with a + (addition) symbol.

A Private access modifier allows only internal access and prevents access by external objects. Private access is denoted on a class diagram with the - (minus) symbol.

The Protected access modifier allows internal access and access by child classes. Protected access is denoted on a class diagram with the # (hash) symbol.

Parent / Generalisation

In figure 2, the BankAccount class is the parent and contains the general state & behaviour for a bank account.

It contains three states - Number, Balance & MinimumBalance. These states have a visibility of Protected to allow the child classes to have access. This is denoted by using the hash (#) character.
Java implementation of Protected BankAccount states:
Protected String _Number;
Protected Decimal _Balance;
Protected Decimal _MinimumAmount;

You will notice that the BankAccount class contains two constructors. We will come back to this shortly but for now, bear in mind that a class constructor prepares a new object for use. It can be handy to provide a number of alternatives for object construction.

As well as the constructors, the class contains a number of getters & setters.

Child / Specialisation

In figure 2, the SavingsAccount & CreditCardAccount classes are children of the BankAccount class. They contain specialised state & behaviour for different types of bank accounts.

The SavingsAccount class contains one specialised state - RATEOFINTEREST. As you can see by the notation (uppercase), this state is a constant & as such it has value. In this case 0.05. From this, we can see that a savings account attracts a 5% rate of interest on the account balance.

The CreditCardAccount class contains one state - INTERESTRATE. Again, the notation (uppercase) denotes that this state is a constant & as such it has value of 0.2. From this, we can see that a credit card account is charged an interest rate of 20% on the balance. (Damn!)

There are no constructors shown in these child classes because in this scenario, the child class constructors will be the same as the parent constructor.

And remember, the child classes also inherit all of the state & behaviour from the parent class. If we were to include all of the inherited state & behaviour in the class diagrams for the child classes, there would be a lot of duplication. Figure 3 below illustrates this.


Figure 3: Unnecessary duplication - Class diagram showing all inherited state & behaviour in the child classes. Larger view

So much unnecessary duplication! Compare figure 3 with figure 2 - they both contain the same detail, however, figure 2 is the usually the most appropriate way to illustrate a class diagram where inheritance is used. That is - the generalised state & behaviour is contained within the parent & the specialised state & behaviour is contained within the child.

Constructors in Inheritance Relationships

The constructor prepares an object for use. Figure 4 shows a simple class diagram where there is no inheritance.


Figure 4: Simple class diagram for the Player class containing a single constructor.
Java implementation of Player constructor:
Public Player(String playerName) {
  _Name = PlayerName;
}

Simple. The constructor executes & completes any work it must do, in this case, assigning the provided parameter to the Name state.

Let’s come back to our inheritance example. Figure 5 below, shows a modified version of our simplified bank account package. We are going to concentrate on one of the constructors within the Parent class (therefore, all of the other behaviours that you might expect to see here, have not been included).


Figure 5: Modified class diagram showing the simplified bank account package.

First, let’s look at the implementation of the constructor in the BankAccount class.
Java implementation of BankAccount constructor
Public BankAccount(String accountNumber, Integer AccountBalance){
    _number = accountNumber;
    _balance = accountBalance;
    _minimumAmount = 0.0;
}

The constructor requires two parameters; the body of the constructor assigns the value of these two parameters to internal state, as well as assigning a value to the minimumAmount state.

Nothing too different so far.

Now let’s have a look at the implementation of the constructors in the child classes. You will notice the use of the statement super. In this scenario, both of the child classes will contain the same implementation so this example is true for both SavingsAccount & CreditCardAccount.

Java implementation of constructor in SavingsAccount class
Public SavingsAccount(String accountNumber, int accountBalance){
    super(accountNumber, accountBalance);
}

super

The super keyword allows calls from the child class to be made on state & behaviour within the parent class (remember, the parent is sometimes also called the base class).

The SavingsAccount constructor immediately calls the constructor of it’s parent, BankAccount. It achieves this by using the keyword super. This keyword causes the constructor of the parent to execute & as such, any required parameters will need to be passed through to it.

Effectively, what happens is that the child constructor passes its own parameters through to the parameters of the parent constructor.

Why must the child constructor call the parent constructor? Well, you wouldn’t be alive without your parents either. Seriously though, the child contains only its own specialised state & behaviour.The parent must be constructed because it contains all of the generalised state & behaviour required by the child classes.

Multiple Constructors

Also called Constructor Overloading, multiple constructors allow object construction to take place in a variety of ways. A number of constructors may be provided within a class, each one accepting a unique parameter list.

Figure 2 shows that the BankAccount class contains two constructors. The following shows the BankAccount constructor discussed in the last section.

Java implementation of BankAccount constructor 1
Public BankAccount(String accountNumber, Integer AccountBalance){
    _number = accountNumber;
    _balance = accountBalance;
    _minimumAmount = 0;
}

Constructor 1 requires two parameters.

Here is the implementation of the second constructor.

Java implementation of BankAccount constructor 2
Public BankAccount(String accountNumber, Integer AccountBalance, Decimal accountMinimumAmount){
    _number = accountNumber;
    _balance = accountBalance;
    _minimumAmount = accountMinimumAmount;
}

Note the difference in the parameter list for constructor 2. It requires three parameters. In fact, each constructor provided within a class MUST contain a unique parameter list.




Constructor Overloading

Multiple constructors may be provided within a class to allow object construction to take place in a variety of ways.

Each constructor MUST have a unique parameter list.

For example:

  • a parameter list of (integer, integer) cannot be duplicated
  • a parameter list of (string, integer) cannot be duplicated

However, a constructor may contain a parameter list of (string, integer) and another constructor may have a parameter list of (string, integer, integer).

The following demonstrates the correct implementation of constructor overloading:

Public Player (String name, Integer credits){}

Public Player (String name, Integer credits, Integer gameID){}

By providing a second constructor in the Player class, a Player object may be instantiated with an additional parameter.

The following is incorrect:

Public Player (String name, Integer credits){}

Public Player (String name, Integer gameID){}


Another example
In this example, we will be concentrating on the two constructors of this Player class (therefore, all of the other behaviours that you might expect to see here have not been included).




Figure 6: Player class with overloaded constructors

When a player logs into the game network,  a new Player object is created with what is known about the player at that time. As the player has not yet joined a game, only the Name and number of Credits is known.

Later on, another player logs into the game network via an alternate method that leads directly to a game that is in progress. As the player has elected which game to join during the login process, the Name, Credits & GameID of the player is known when the new Player object is created.


Abstract Classes

As mentioned above, an abstract class is a class that is designed to provide common state & behaviour for it’s child classes but is not designed to have instances of itself. That is - an abstract class cannot be directly instantiated; only it’s children may be instantiated.

Let’s now return to the original class diagram of our simplified bank account package.


Figure 7: The simplified bank account package class diagram. Larger view

Consider the following questions:
  1. When should an object of the BankAccount class be instantiated?
  2. Should it ever be instantiated at all?
  3. If not, why not?

Object Oriented Design can be very subjective, as such, we need to rely on what we know about the system/package. In this case, all we have to rely on or make assumptions about, is this snippet of a scenario (from earlier):
There are two types of bank accounts - a savings account that attracts a 5% rate of interest on the balance and a credit card account that charges 20% interest on the balance. All bank accounts have also have a number and may or may not have a minimum balance imposed on them.


While a generalised BankAccount class has been included in the diagram, there does not seem to be a case for instantiating an object of that class.

The SavingsAccount & CreditCardAccount classes on the other hand, seem to be the main players in this scenario. In fact, there does not seem to be a need to ever instantiate a BankAccount object, it seems to have no practical use (apart from aggregating all common state & behaviour of child classes). In this scenario, the only objects we want hanging around in the system are those belong to the child class types.

Therefore, we call the BankAccount class an Abstract class.
(Abstract, adjective: Not applied or practical; theoretical)

While a keenly aware developer with access to good information may realise that only SavingsAccount & CreditCardAccount objects should be instantiated, it is important that we implement measures to prevent an abstract class from being instantiated.

UML Notation: Abstract Class

Look at figure 7 and notice that the name of the BankAccount class is now in italics (It would not render out correctly in the PDF). This is the correct notation for an abstract class name in a class diagram.

Java implementation of Abstract BankAccount Declaration:
Public abstract Class BankAccount

abstract Keyword

The abstract keyword used in the class declaration, ensures that objects of the class cannot be instantiated. So while the class still exists, it exists only to pass on genes to its children - that is, it exists only to provide common state & behaviour to child objects.

And while we are on the subject, the child classes; the ones that can be instantiated, are said to be Concrete classes because they can be instantiated.

Examples are given below:

Incorrect (will not compile)
BankAccount ThisBankAccount = New BankAccount(.....

Correct
SavingsAccount ThisBankAccount = New SavingsAccount(.....
CreditCardAccount ThisBankAccount = New CreditCardAccount(.....



Another Example

This package is another inheritance example containing an abstract class. It contains many similarities to the simplified bank account package - but there are some differences.

Scenario: Tribe

There is a Red tribe & a Blue tribe. The Red tribe has a secret password of “umma gunna” & may or may not have a queen. The Blue tribe has a maximum population of 300. Both tribes have a dialect & contain a number of members. The Red tribe always has a function it performs in society whereas the Blue tribe may or may not have a function at any given time.


Figure 8: Tribe package class diagram. Larger View

Note: The larger view PDF has not rendered out the italics of the abstract class name (Tribe).

Abstract Methods (abstract behaviours)

Abstract classes can also contain abstract methods.

As an abstract class can never be directly instantiated, we can think of it’s members (state & behaviour) as a control panel, or an interface. We can still call the behaviours that exist in the abstract class, but only in the context of a child class.

An abstract method must be declared within an abstract class. The method itself, contains no implementation. It then becomes a requirement for any child classes to implement the method.

Consider a scenario where all child classes must provide their own implementation of a  CalculateRebate behaviour. Each implementation of this behaviour in the scenario must be different as each class calculates rebates according to a different rationale.

The following shows an abstract method signature in an abstract class.
Java implementation of an abstract method in an abstract class:
Public abstract Integer calculateRebate();

Notice the use of the abstract keyword in the method signature. This enforces the implementation of the method in all child classes. An abstract method contains no implementation (contains no code).

One of the beauties of object oriented design & programming is the ability to allow others to inherit from and extend your classes at a later date. Abstract methods can help to ensure that certain rules are enforced across a package.

Abstract methods are useful when you need to ensure that all child classes (both the ones you that you create & the ones that may be created later) contain their own implementation of the method.

Scenario: Rebate


There is a government rebate available for singles and families. The unadjusted amount of the rebate is $10.00 per person, however this amount is adjusted according to circumstances. Singles may only claim the rebate if their income is below $85,000. Families receive a rebate bonus of an extra 10% per dependant.


Figure 9: Rebate package class diagram. Larger view
This class diagram does not include other methods you may expect to see here such as getters & setters. The emphasis is on the abstract method CalculateRebate, contained within the abstract class Rebate, which is inherited by each of the child classes. Notice that the abstract method name is denoted with italic text. (Once again, the PDF in the larger view has not correctly rendered the italic text.)

See also:

"Object-oriented design - Wikipedia, the free encyclopedia" ( http://bit.ly/cbnJAY )
"InformIT: Object-Oriented Analysis and Design > History" ( http://bit.ly/9GpyYl )
"Object-oriented programming - Wikipedia, the free encyclopedia" ( http://bit.ly/cLXHSq )