Sunday 25 December 2011

Encapsulation in Java

Encapsulation is the concept of hiding the implementation details of a class and allowing access to the class through a public interface. For this, we need to declare the instance variables of the class as private or protected. The client code should access only the public methods rather than accessing the data directly. Also, the methods should follow the Java Bean's naming convention of set and get.

Encapsulation makes it easy to maintain and modify code. The client code is not affected when the internal implementation of the code changes as long as the public method signatures are unchanged. For instance:

public class Employee
{


private float salary;


public float getSalary()
{


return salary;


}
public void setSalary(float salary)
{


this.salary = salary;


}



IS-A relationship


The IS-A relationship is based on inheritance. In Java programming, it is implemented using the keyword extends. For instance:

public class Animal {...}
public class Cat extends Animal
{


// Code specific to a Cat. Animal's common code is inherited


}


Here Cat extends Animal means that Cat inherits from Animal, or Cat is a type of Animal. So Cat is said to have an IS-A relationship with Animal.

HAS-A relationship


If an instance of class A has a reference to an instance of class B, we say that class A HAS-A B. For instance:

class Car
{


private Engine e;


}
class Engine {}


Here the Car class can make use of the functionality of the Engine class, without having the Engine class's specific methods in it. This gives us a chance to reuse the Engine class in multiple applications. Thus the HAS-A relationship allows us to have specialized classes for specific functions.

No comments:

Post a Comment