Thursday, January 21, 2016

Topic 18: Access Control in Java

How a member can be accessed is determined by the access specifier. 

  • Java supplies a rich set of access specifiers like public, private, and protected. Java also defines a default access level.

  • protected - applies only when inheritance is involved.

  • public - member can be accessed by any other code.

  • private - member can only be accessed by other members of its class.


  • When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.


To understand the effects of public and private access, consider the following fragment:

// Inside class Test
int a; // default access
public int b; // public access
private int c; // private access


// methods to access c
void setc(int i)
{
// set c's value
c = i;
}

int getc()
{
// get c's value
return c;
}

//Inside class containing main()

Test ob = new Test();

// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;

// This is not OK and will cause an error
//ob.c = 100; // Error!

// We must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());


Inside the Test class, “a” uses default access. “b” is explicitly specified as public. Member “c” is given private access. This means, “c” directly cannot be accessed by code outside of its class. But using its public methods: setc( ) and getc( ), we can access “c”.



Click for NEXT article.


Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment