Wednesday, December 18, 2013

Java Controlling Access to Members of a Class

This is one of the most important basics of java where still programmers often get confused.
Java basically has four access modifiers

  1. public 
  2. protected
  3. no modifier/ default modifier
  4. private
Basically everybody is comfortable with understanding public and private access modifiers and confusion tend to have with default modifier and protected modifier.

So going from very basics, public gives access to whole world or all with the very true meaning of the word. private gives access only to class or class level access only. In simple outside the class nobody can access it.

protected - this specifies that memebers can be accessed only withing package and by via a sub class of its class in another package.
The last term - by subclass of its class - in another package ( This is the imporatant condition where makes the difference with the default access modifier)

no modifier/ default access modifier - we can also call package private , makes visibility only within the package.( no visibility to subclass of its class in another package - that's why it called package private)


The following table summarises four access levels
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N


Table columns explains as follows.
Class - whether the class itself has access to the members defined by the class
Package - whether classes in the same package as the class (regardless of the parentage ) can access the members of the class
Subclass - whether subclass of the class defined outside the class package can acess the mebers of the class
world - whether all classes has the ability to access the memebers of the class(irrespective of the package/ location )

The following example will help to understand avpve table more precisely.

Table explains whther the members of the Alpha class are visible to others
Alpha - the class
Beta - class in the same package as Alpha
AlphaSub - subclass of  Alpha in different package from Alpha class
Gamma - class in a different package from Alpha


Visibility
Modifier Alpha Beta Alphasub Gamma
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N