Monday, 26 October 2015

Access Modifiers with example

Public:

 As the name species it it available to all, means the members marked public are available within and outside the class.

Example:

public class A {
  public int add(int a, int b)
  {
    return a + b;
  }
class B {
   A a = new A( );
   a.add(5,4);  // This method is available as it is public in nature
}


Private:

 It is available only within the class.


Example:

public class A {
  private int add(int a, int b)
  {
    return a + b;
  }
class B {
   A a = new A( );
   a.add(5,4);  // This will give error as the method is marked private so it is not available                           outside the class
}

Protected : 

Members marked protected are available within the class and by derived class instances.

Example:

public class A {
  protected int add(int a, int b)
  {
    return a + b;
  }
class B:A    // Inherit A class 
{
   A a = new A( );
   a.add(5,4);  // This will give error as the method is marked protected so it is not                                       available outside the class

           B b = new B( );
           b.add(5,4);  / / This will work fine as we can call protected method using derived class                                                  instance.
}

Internal : 

Internal types or members are accessible only within files in the same assembly.


No comments:

Post a Comment