Thursday, July 23, 2009

Class Abstraction and Encapsulation

Abstract classes provide a way to force an inherited class to impliment an override method, similar to, but not the same as an interface.

Unlike an interface, abstract classes are fully functional classes, but you can force one or more methods to be overridden.

Lets say you had a theoretical vehicle class. Every vehicle must be able to steer (i.e. must have a steer() method) however different types of vehicle will have different implementation of this method. It is pointless to implement this method in the base class as the code will not be used, but dangerous to leave it empty as it could be called and the resulting vehicle will be unable to steer. By marking the method as abstract, you force any derived classes to have their own implementation of the method.

abstract class Vehicle
{
abstract public void steer();
}

Because there is no implementation of the steer method, the statement is terminated with a semi-colon. If one or more methods are marked as abstract, then the class must also be marked as abstract.

Now, each class that inherits from the Vehicle class must implement the steer method.

public class Car : Vehicle
{
public override void steer()
{
// Implement a steering wheel
}
}

public class Bike : Vehicle
{
public override void steer()
{
// Implement handlebars
}
}

public class Tank : Vehicle
{
public override void steer()
{
// Implement tracked drive steering
}
}

public class Airplane : Vehicle
{
public override void steer()
{
// Implement ailerons and rudders
}
}

This ensures that all inherited classes always have a specific implementation of the abstract method.

Encapsulation

Encapsulation is the ability for an object to hide its data and methods from those who do not need to know, and only expose data and methods that are required.

Techniques for encapsulation include class abstraction and properties. Sometimes you may not wish direct interaction with an objects data fields, for example in a bank account class you would not want to expose a balance field where it could possibly be modified without any checks or security.

Abstraction is the process of protecting the data using properties, so that any attempt to modify the data is done through the proper channels, ideally with an audit log for the bank account class.

No comments:

Post a Comment