Encapsulation,Inheritance


        Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

# Encapsulation:
ð  It is called the data abstraction or data hiding.
ð  Encapsulation is the technique of making the fields in a class private and providing access to the fields via 
public methods.
ð  If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

v  Benefits of Encapsulation:
ð  The fields of a class can be made read-only or write-only.
ð  A class can have total control over what is stored in its fields.
ð  The users of a class do not know how the class stores its data. A class can change the data type of a field, and users of the class do not need to change any of their code. 

Example:
v  public class EncapTest{

   private String name;
   private int age;
   public String getName(){
      return name;
   }
   public int getAge(){
      return age;
   }
   public void setName(String newName){
      name = newName;
   }
   public void setAge( int newAge){
      age = newAge;
   }
}

v  public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      System.out.print("Name : " + encap.getName()+" Age : "+ encap.getAge());
    }
}

ð  The public methods are the access points to this class fields from the outside java world. Normally these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

# Inheritance:
ð  Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.
ð  For inheritance the most commonly used keyword would be “extends” and “implements”.
ð  With use of the “extends” keyword the subclasses will be able to inherit all the properties of the super class except for the private properties of the super class.
ð  This relationship helps to reduce duplication of code as well as bugs.
ð  Java only supports only single inheritance. This means that a class cannot extend more than one class.
ð  However a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance

No comments:

Post a Comment