CSC/ECE 517 Fall 2011/ch1 2b rv: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
 
(93 intermediate revisions by 2 users not shown)
Line 1: Line 1:
'''Access Control in O-O Languages
__TOC__
__TOC__
=Introduction to Access control=
=Introduction to Access control=
In object oriented programming, access control refers to the control of visibility of data and methods. The main idea behind access control is to hide the underlying implementation of functions behind its public interface. Access control implements encapsulation by providing varying levels of access to code. The use of access control becomes necessary in any practical environment where selective access is a key criterion.  
 
For example, only the instructor can be allowed to modify grades of students but all students should be given access to retrieve and view their respective grades.   
<p>In [http://en.wikipedia.org/wiki/Object-oriented_programming object oriented programming], access control refers to the control of visibility of data and methods. The main idea behind access control is to restrict access to certain parts of the code to external entities. Access control implements [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) encapsulation] by providing varying levels of access to code. The use of access control becomes necessary in any practical environment where selective access is a key criterion. </p>
Access control in different object oriented languages and the underlying details will be covered in this topic.
<p>For example, only the instructor can be allowed to modify grades of students but all students should be given access to retrieve and view their respective grades.</p>  
<p>Access control in different object oriented languages and the underlying details will be covered in this topic.</p>
 
=Overview of Access Control Mechanisms=
=Overview of Access Control Mechanisms=
Each O-O language has a specific implementation of access control mechanisms. However, a plethora of the most widely used o-o languages share similar features while implementing access control. Access control mechanisms are applicable to methods and functions. Some access level control can be applied at the class level. The 3 basic types of access control implementation which is common to some static and dynamic O-O languages [like C++, C#, Java and Ruby] are <br>
 
Each O-O language has a specific implementation of access control mechanisms. However, a plethora of the most widely used o-o languages share similar features while implementing access control. Access control mechanisms are applicable to class members like variables and functions. Some level of access control can be applied at the class level. The 3 basic types of access control implementation which is common to some [http://en.wikipedia.org/wiki/Static-typing_%28programming_languages%29#Static_and_dynamic_typing static and dynamic O-O languages] [like C++, C#, Java and Ruby] are <br>
<br>
<br>
'''Public''' : Methods or attributes that are declared to be public can be accessed from any class. This is the least restrictive access control method.  
'''Public''' : Methods or attributes that are declared to be public can be accessed from any class. This is the least restrictive access control method. For example, we may want everyone in a company to know the names of people working along with them. Thus public access is given to employee's name.


'''Private''' : This mechanism declares the data or method to be visible only in the class in which it is declared. The support is not extended to sub classes. This is the most restrictive access control method.  
'''Private''' : This mechanism makes the data or method to be visible only in the class in which it is declared. The support is not extended to sub classes. This is the most restrictive access control method.  
In any application, methods which implement the core functionality or require administrator access are declared to be private thereby enforcing limited access. For example, only a manager can be given the authority to review an employee’s performance and award bonus and promotions.  
In any application, methods which implement the core functionality or require administrator access are declared to be private thereby enforcing limited access. For example, only a manager can be given the authority to review an employee’s performance and award bonus and promotions.  


'''Protected''' : The use of protected access allows access of data and methods to be modified by members belonging to the same family. This means that this support is extended to subclasses. Protected access control is widely used to support the single interface, multiple implementation concept i.e, inheritance.  
'''Protected''' : The use of protected access allows access of data and methods to be modified by members belonging to the same family. This means that this support is extended to subclasses. Protected access control can be used to support the single interface, multiple implementation concept i.e, [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) inheritance].  
For example, a super class may have a protected method called ComputeArea(). We can have many subclasses like Triangle, Rectangle etc inherit the super class and override the method ComputeArea() to provide their own specific implementation.
For example, a super class may have a protected method called ComputeArea(). We can have many subclasses like Triangle, Rectangle etc inherit the super class and override the method ComputeArea() to provide their own specific implementation. In a more practical scenario, a person might be allowed to view the medical history of immediate family members. However, people outside the family will not be allowed access to view this medical history.  


=Implementing Access Control=
=Implementing Access Control=


Access control is implemented in different languages in their own way. We present a few of the languages that use access control and show their implementation.
Programming languages implement access control in different ways. We present a few of the languages that use access control and show their implementation.


=='''Java'''==
=='''Java'''==
In Java, access control is achieved using the modifiers public, private and protected. If a class is not declared with any modifier, then the default access becomes package-private i.e, any object within the package should be able to access this class.  
In Java, access control is achieved using the modifiers public, private and protected. If a class is not declared with any modifier, then the default access becomes package-private i.e, any object within the package should be able to access this class.  
   
   
Public Keyword – Other classes can modify public fields unless its declared as final. The syntax for declaring a variable/function public is as follows <br>
<p>'''Public Keyword''' – Other classes can modify public fields unless its declared as [http://en.wikipedia.org/wiki/Final_%28Java%29 final]. The syntax for declaring a variable/method public is as follows <br></p>
                public int x; <br>
<pre>public int x;
                public <return type> <function name> - public void print_Hello() <br>
public void print_Hello()</pre>
In the example shown below, the variables studentName and studentID are declared to be public. The public methods like getName() etc become accessible by other classes. <br>
Private Keyword – This keyword makes the class members private. Private members can only be accessed from within the class. They are not visible even in subclasses. However, visibility and access of private members is extended to nested classes. The syntax for declaring a variable/function private is as follows
                private String EmpID;
                private <return type> <function name> - private void getEmpDetails()
In the example code below, the function setID is declared to be private. Hence, it cannot be accessed in the subclass of the class CSC_517. <br>


Protected Keyword – This keyword when used before a class member makes that member visible to the elements residing in that class and its subclasses. The syntax for declaring a variable/function protected is as follows
In the example shown below, the variable studentName is public and hence can be accessed in another class Student2. Similarly, public methods like getName() etc become accessible by other classes. <br>
                protected int sides;
<p>'''Private Keyword''' – This keyword makes the class members private. Private members can only be accessed from within the class. They are not visible even in subclasses. However, visibility and access of private members is extended to nested classes. The syntax for declaring a variable/method private is as follows</p>
                protected <return type> <function name> - protected void setArea(int sides)  
<pre>private String EmpID;
private void getEmpDetails() </pre>


In the example code below, the function setName is declared as protected. Hence, it can be accessed in the subclass NewStudent. <br>
<p>In the example code below, the method setID is declared to be private. Hence, it cannot be accessed in the subclass of the class Student.</p>


Default access level/Package When no specific access control keyword is given, then the method or variable becomes accessible to all classes under a particular package. In the following example, the integer “packageVar” becomes accessible to all classes included in the package ‘TestPackage1’.
<p>'''Protected Keyword''' This keyword when used before a class member makes that member visible to the elements residing in that class and its subclasses. However if the subclass is in a different package, then the protected member is visible only through inheritance. It cannot be accessed by the object of the parent class as the definition is in another package. The syntax for declaring a variable/method protected is as follows</p>
<pre>protected int sides;
protected void setArea(int sides)</pre>


<code>
<p>In the example code below, the method setName is declared as protected. Hence, it can be accessed in the subclass NewStudent.</p>


package TestPackage1 <br>  
<p>'''Default access level/Package''' – When no specific access control keyword is given, then the method or variable becomes accessible to all classes under a particular package. In the following example, the integer “packageVar” becomes accessible to all classes included in the package ‘TestPackage1’. Hence, it can be modified in the class Student2.</p>


public class CSC_517 { <br>
<pre>
 
Example:
 
package TestPackage1 
public class Student {


public String studentName;
public String studentName;
Line 76: Line 85:
}
}
}
}
</code>
public class Student2 {
        public static void main(String[] args) {
                Student Stu2 = new Student();
                Stu2.studentName = "Mickey";    //Public variable of another class can be accessed
                Stu2.packageVar = 5;            //Default access level
        }
}
</pre>


=='''C++==
=='''C++==
In C++, we have the three modifiers presented in the overview along with a special type of access control called [http://en.wikipedia.org/wiki/Friend_function friend]. The behavior of public, private and protected modifiers is similar to its Java counterparts.


In C++, we have the three modifiers presented in the overview along with a special type of access control called “friend”. The behavior of public, private and protected modifiers is similar to its Java counterparts.
<p>Friend - A function or class can access the private and protected members of a class if it is declared as a friend of that class. </p>
Friend - A function or class can access the private and protected members of a class if it is declared as a friend of that class.  


<code>
<pre>
class Number
class Number
{ int a,b;
{ int a,b;
Line 93: Line 109:
private:
private:
int prod(int,int);
int prod(int,int);
int add(int a,int b)
int add(int a,int b)
{
{
Line 124: Line 142:
}
}


</code>
</pre>
 


'''More about friend functions.
'''More about friend functions'''


If a class is declared as a friend in another class, the friend class can access all the private members of the class. This can also be limited in such a way that only few private members of the class can be accessed.
<p>If a class is declared as a friend in another class, the friend class can access all the private members of the class. This can also be limited in such a way that only few private members of the class can be accessed. By using friend functions or classes, we can provide a flexibility of letting a friend class access restricted members of a class and still keeping the restricted members closed for access by any other class. This will be useful in a few cases.</p>
By using friend functions or classes, we can provide a flexibility of letting a friend class access restricted members of a class and still keeping the restricted members closed for access by any other class. This will be useful in a few cases.


=='''Ruby==
=='''Ruby==
Ruby provides the three levels of access controls, private, public and protected with the default being public access. The behavior of public and protected access control is similar to other languages like C++ and Java.
<p>However, private methods can be called only within the context of the current object. Other object’s private method cannot be invoked. Private methods can be overridden by the sub-classes.In most cases, private methods are used to provide internal functionality to the class. So we need to use a cautious approach in using private methods. If they are overridden by the subclass, we tend to get unexpected behavior in the program.</p>


Ruby provides the three levels of access controls, private, public and protected with the default being public access. The behavior of public and protected access control is similar to other languages like C++ and Java.
<p>'''Note''': Private methods cannot be called outside of the class. Private methods can be called only using the “send” method. </p>
Private - Private methods can be called only within the context of the current object. Other object’s private method cannot be invoked. Private methods can be overridden by the subclasses.
In most cases Private methods are used to provide internal functionality to the class. So we need to use a cautious approach in using private methods. If they are overridden by the subclass, we tend to get unexpected behavior in the program.
Note: Private methods cannot be called outside of the class. Private methods can be called only using the “send” method. However, this violates the private functionality and should not be used.


<code>
<pre>
class Number
class Number
   def initialize(a,b)
   def initialize(a,b)
Line 164: Line 181:
Num1.add(Num1)
Num1.add(Num1)
Num1.diff(Num1)
Num1.diff(Num1)
</code>
</pre>
 
<p>This program runs successfully and prints the output as long as the private method is not accessed. Here, the private method is num2 and should not be invoked in the current context of the object.</p>


This program runs successfully and prints the output, only as long as the line with private is commented. If the method num2 is declared as private, then we get the error below.
<pre>in `add': private method `num2' called for #<Number:0x436e18 @number1=50, @number2=60> (NoMethodError)</pre>


in `add': private method `num2' called for #<Number:0x436e18 @number1=50, @number2=60> (NoMethodError)
However, the private method num2 can be accessed using the send method. The syntax for accessing the method is '''a.send(:num2)


=='''C#==
=='''C#==
It has 5 specific levels of access control at the class member level.
<p>'''1. Public''' : Public access is the least restrictive access level and class members can be accessed anywhere. </p>
<p>'''2. Private''' : Private is the most restrictive access level where members are accessed only in the body of the class in which they are declared. This support is also extended to nested classes. </p>
<p>'''3. Protected''' : The protected keyword is a member access modifier i.e, it cannot be applied at a class level. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.</p>


It has 5 specific levels of access control at the class member level
<pre>
1. Public : Public access is the least restrictive access level and class members can be accessed anywhere.
2. Private : Private is the most restrictive access level where members are accessed only in the body of the class in which they are declared. This support is also extended to nested classes.
3. Protected : The protected keyword is a member access modifier i.e, it cannot be applied at a class level. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.


<code>
class Number
class A
{
{
public int x;
public int x =5;
protected int y = 20;  
        public int y =10;  
private int c;
public int add() {
public double AccessC() {
       return x+y;
       return c;
   }
   }
protected int diff(){
return y-x;
}
private int prod(){
return x*y;
}
}
}


class B
class Number1
{
{
public static void Main()
public static void Main()
{
{
A ax = new A();
Number num = new Number();
ax.x = 10; //access to public members
num.add(); //access to add
ax.c = 5; // can't as 'c' is declared private
num.diff(); // can't as diff is declared protected
int try = ax.AccessC(); // error thrown as 'c' is private
num.prod(); // can't access as prod is private
}
}
}
}


class C : A
class Number2 : Number
{
{
public static void Main()
public static void Main()
{
{
A a2 = new A();
Number2 num2 = new Number2();
a2.y = 10; // access to protected member
num2.diff(); // access to protected member
}
}
}
}
</code>
</pre>


4. Internal : It is an access modifier for types and type members. Internal members are accessible only within files in the same assembly.
<p>'''4. Internal''' : It is an access modifier for types and type members. Internal members are accessible only within files in the same assembly.</p>
<p>'''5. Protected Internal''': This access control restricts access of members to the class, subclass within the assembly. The difference between protected internal and internal is that, a subclass of the class derived in another assembly can also access the protected internal method.</p>


<pre>
File1.cs:
File1.cs:
class Class1
class Number3
{
{
   internal static int Random = 0;
   internal int x =0;
   protected internal int Access = 0;
   protected internal int y = 0;
}
}
File2.cs
File2.cs
class Class2 : Class1
class Number4 : Number3
{
{
  public static void Main()  
  public static void Main()  
  {
  {
       Class1 c1 = new Class1();   
       Number4 num4 = new Number4();   
c1.Random = 4 // error, Class1 not visible outside assembly
      num4.x = 4 // error, as x is declared as internal
              c1.Access = 5 // Allowed. As Access is protected internal.
      num4.y = 5 // Allowed. As y is protected internal.
  }
  }
}
}
 
</pre>
5. Protected Internal: This access control restricts access of members to the class, subclass within the assembly. The difference between protected internal and internal is that, a subclass of the class derived in another assembly can also access the protected internal method.


=='''Python==
=='''Python==
<p>Python implements access control in a different way from most other languages in that they don’t have specific access control modifiers. By default all members are public and we precede the member name with ‘__’ (a double underscore) to indicate if the member is private. This feature of python is called as [http://en.wikipedia.org/wiki/Name_mangling Name Mangling]. </p>


Python implements access control in a different way from most other languages in that they don’t have specific access control modifiers. By default all members are public and we precede the member name with ‘__’ (a double underscore) to indicate if the member is private. This feature of python is called as “Name Mangling”.
<p>There is no feature in python to implement the protected access control. </p>
There is no feature in python to implement the protected access control.  


<code>
<pre>
class Number:
class Number:
   def __init(self,a,b): // this is a private method
   def __init(self,a,b): // this is a private method
Line 250: Line 276:
Num1.add()
Num1.add()
Num1.diff()
Num1.diff()
</code>
</pre>


Note that in python the __init method is made to be private as default while programming.  
<p>Note that in python the __init method is made to be private as default while programming. </p>


'''More on Name Mangling
'''More on Name Mangling in Python
Name mangling is a feature of python using which we indicate whether a member is private by just adding underscores, instead of using key words. When we program or debug, it is easier to note that the member is private and thus refrain from accessing it.  
<p>Name mangling is a feature of python using which we indicate whether a member is private by just adding underscores, instead of using key words. When we program or debug, it is easier to note that the member is private and thus refrain from accessing it.</p>


==Eiffel==
=='''Eiffel==
Eiffel has a different approach to access control compared to the previous object oriented languages like C++ and Java. It uses ''selective export'', which means that different methods and attributes can have different access levels. Also, we can individually specify the access level for each method or attribute.


Eiffel has a different approach to access control compared to the previous object oriented languages like C++ and Java. It uses selective export which means that different methods and attributes can have different access levels. Also, we can individually specify the access level for each method or attribute.
<pre>
 
<code>
class Number
class Number
feature{NONE} -- indicates nothing can access this code from outside of the                       class(private)
feature{NONE} -- indicates nothing can access this code from outside of the class (private)
a: INTEGER
a: INTEGER
b: INTEGER
b: INTEGER
Line 284: Line 309:
end
end
end
end
</code>
</pre>


'''More on feature:
'''More on feature:
Using feature, we can provide varying levels of access to a code in the class. And also we can provide the names of classes that are only allowed to access that part of the code. In the above example, the different access levels that features provide are explained in the comments.
<p>Using feature, we can provide varying levels of access to a code in the class. And also we can provide the names of classes that are only allowed to access that part of the code. In the above example, the different access levels that features provide are explained in the comments.</p>


=Comparison among different O-O languages=
=Comparison among different O-O languages=


=Note about usage of Access Control=
{|class="wikitable"
With many access control mechanisms defined, there is always the question of which access control can be used. This is decided at the discretion of the programmer but as a good programming practice, the following can be used.
|-
!
!Java
!C++
!C#
!Ruby
!Python
!Eiffel
|-
|Public
|Can be accessed outside of class
|Can be accessed outside of class
|Can be accessed outside of class
|Can be accessed outside of class
|Can be accessed outside of class
|Can be accessed outside of class
|-
|Protected
|Access within the class and sub-classes
|Access within the class and subclasses
|Access within the class and subclasses
|Access within the class and subclasses
|No protected access
|Access can be given to only a few of the classes.
|-
|Private
|Cannot be directly accessed from outside the class. Can be accessed by nested classes.
|Cannot be directly accessed from outside the class
|Cannot be directly accessed from outside the class
|Cannot be directly accessed from outside the class
|Cannot be directly accessed from outside the class
|Cannot be directly accessed from outside the class
|-
|Special feature
|Default access is package. Any class in a package can access if no modifier is given
|friend functions(access of private to a specific friend class or method)
|internal and protected internal
|send method is used to access private members
|Name Mangling(use of underscores to indicate access level)
|Selective export using "feature"
|}
 
=A short note on the usage of Access Control=
 
As a good programming practice, the following guidelines can be used to implement access control mechanisms.
 
1. Use public access only if an interface for a class so that the data can be sent or modified based on external requirements.
1. Use public access only if an interface for a class so that the data can be sent or modified based on external requirements.
2. Use of private is advisable whenever we program the internal structure of the program, like the constructors. Some languages, like Ruby make their variables private by default so that modifications from external entities are avoided.
<p>2. Use of private is advisable whenever we program the internal structure of the program, like the constructors. Some languages, like Ruby make their variables private by default so that modifications from external entities are avoided.</p>


=Summary=
Access control provides powerful mechanism to implement encapsulation and it can find its use in several applications. However, if not used with caution, access control can lead to unexpected behavior in the program. It is always important to use the right access control to avoid ambiguity and ease the maintainability of code.
Access control provides powerful mechanism to implement encapsulation and it can find its use in several of the applications. However, if not used with caution, access control can lead to unexpected behavior in the program. It is always important to use the right access control for the situation to avoid ambiguity and ease the maintainability of code.


=References=
=References=


http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html <br>
* [http://en.wikipedia.org/wiki/Object-oriented_programming Object Oriented Programming]<br>
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html <br>
* [http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming) Encapsulation]<br>
http://msdn.microsoft.com/en-us/library/kktasw36(v=VS.80).aspx <br>
* [http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html Access Control in Java] <br>
http://www.exforsys.com/tutorials/c-plus-plus/c-plus-plus-friend-functions.html <br>
* [http://msdn.microsoft.com/en-us/library/kktasw36(v=VS.80).aspx Member Access Control in C++]<br>
http://en.wikipedia.org/wiki/Friend_function <br>
* [http://www.exforsys.com/tutorials/c-plus-plus/c-plus-plus-friend-functions.html C++ friend functions]<br>
http://rubylearning.com/satishtalim/ruby_access_control.html <br>
* [http://en.wikipedia.org/wiki/Friend_function Implementing friend functions]<br>
http://docs.python.org/release/1.5/tut/node67.html <br>
* [http://msdn.microsoft.com/en-us/library/ms173121.aspx Access Modifiers in C#] <br>
http://www.tutorialspoint.com/python/python_classes_objects.htm <br>
* [http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html Programming Ruby] <br>
http://www.maths.tcd.ie/~odunlain/eiffel/eiffel_course/eforb.htm <br>
* [http://rubylearning.com/satishtalim/ruby_access_control.html Access Control in Ruby]<br>
http://en.wikipedia.org/wiki/Eiffel_(programming_language)<br>
* [http://en.wikipedia.org/wiki/Name_mangling Name Mangling in OO Langugages]<br>
http://www.maceiffel.com/Into%20Eiffel.pdf <br>
* [http://docs.python.org/release/1.5/tut/node67.html Name Mangling in Python]<br>
http://msdn.microsoft.com/en-us/library/ms173121.aspx <br>
* [http://www.tutorialspoint.com/python/python_classes_objects.htm Class Objects in Python] <br>
* [http://www.maths.tcd.ie/~odunlain/eiffel/eiffel_course/eforb.htm Eiffel for Beginners]<br>
* [http://en.wikipedia.org/wiki/Eiffel_(programming_language) More on Eiffel]<br>
* [http://www.maceiffel.com/Into%20Eiffel.pdf Into Eiffel By Ian Joyner]<br>
* [http://en.wikipedia.org/wiki/Static-typing_%28programming_languages%29#Static_and_dynamic_typing Static and Dynamic Typing]<br>

Latest revision as of 00:38, 1 October 2011

Access Control in O-O Languages

Introduction to Access control

In object oriented programming, access control refers to the control of visibility of data and methods. The main idea behind access control is to restrict access to certain parts of the code to external entities. Access control implements encapsulation by providing varying levels of access to code. The use of access control becomes necessary in any practical environment where selective access is a key criterion.

For example, only the instructor can be allowed to modify grades of students but all students should be given access to retrieve and view their respective grades.

Access control in different object oriented languages and the underlying details will be covered in this topic.

Overview of Access Control Mechanisms

Each O-O language has a specific implementation of access control mechanisms. However, a plethora of the most widely used o-o languages share similar features while implementing access control. Access control mechanisms are applicable to class members like variables and functions. Some level of access control can be applied at the class level. The 3 basic types of access control implementation which is common to some static and dynamic O-O languages [like C++, C#, Java and Ruby] are

Public : Methods or attributes that are declared to be public can be accessed from any class. This is the least restrictive access control method. For example, we may want everyone in a company to know the names of people working along with them. Thus public access is given to employee's name.

Private : This mechanism makes the data or method to be visible only in the class in which it is declared. The support is not extended to sub classes. This is the most restrictive access control method. In any application, methods which implement the core functionality or require administrator access are declared to be private thereby enforcing limited access. For example, only a manager can be given the authority to review an employee’s performance and award bonus and promotions.

Protected : The use of protected access allows access of data and methods to be modified by members belonging to the same family. This means that this support is extended to subclasses. Protected access control can be used to support the single interface, multiple implementation concept i.e, inheritance. For example, a super class may have a protected method called ComputeArea(). We can have many subclasses like Triangle, Rectangle etc inherit the super class and override the method ComputeArea() to provide their own specific implementation. In a more practical scenario, a person might be allowed to view the medical history of immediate family members. However, people outside the family will not be allowed access to view this medical history.

Implementing Access Control

Programming languages implement access control in different ways. We present a few of the languages that use access control and show their implementation.

Java

In Java, access control is achieved using the modifiers public, private and protected. If a class is not declared with any modifier, then the default access becomes package-private i.e, any object within the package should be able to access this class.

Public Keyword – Other classes can modify public fields unless its declared as final. The syntax for declaring a variable/method public is as follows

public int x;
public void print_Hello()

In the example shown below, the variable studentName is public and hence can be accessed in another class Student2. Similarly, public methods like getName() etc become accessible by other classes.

Private Keyword – This keyword makes the class members private. Private members can only be accessed from within the class. They are not visible even in subclasses. However, visibility and access of private members is extended to nested classes. The syntax for declaring a variable/method private is as follows

private String EmpID; 
private void getEmpDetails() 

In the example code below, the method setID is declared to be private. Hence, it cannot be accessed in the subclass of the class Student.

Protected Keyword – This keyword when used before a class member makes that member visible to the elements residing in that class and its subclasses. However if the subclass is in a different package, then the protected member is visible only through inheritance. It cannot be accessed by the object of the parent class as the definition is in another package. The syntax for declaring a variable/method protected is as follows

protected int sides; 
protected void setArea(int sides)

In the example code below, the method setName is declared as protected. Hence, it can be accessed in the subclass NewStudent.

Default access level/Package – When no specific access control keyword is given, then the method or variable becomes accessible to all classes under a particular package. In the following example, the integer “packageVar” becomes accessible to all classes included in the package ‘TestPackage1’. Hence, it can be modified in the class Student2.


Example:

package TestPackage1  
public class Student {  

	public String studentName;
	public int studentID;
	int packageVar;

	public String getName() {
		return studentName;
	}
	public int getID() {
		return studentID;
	}
	protected void setName(String s) {
		studentName = s;
	}
	private void setID(int y) {
		studentID = y;
	}
	public static void main(String[] args) {
		Student Stu1 = new Student();
		Stu1.setName("ABCD");
		Stu1.setID(1230013);
		System.out.println(Stu1.getName() + Stu1.getID());
	}
}
public class NewStudent extends Student {	
	public static void main(String[] args) {
		NewStudent NewStu1 = new NewStudent();
		NewStu1.setName("EFGH"); 		//Can be accessed 
		NewStu1.setID(350);		// Cannot be accessed as setID is private
		System.out.println(NewStu1.getName());
	}
}
public class Student2 {
        public static void main(String[] args) {
                Student Stu2 = new Student();
                Stu2.studentName = "Mickey";     //Public variable of another class can be accessed
                Stu2.packageVar = 5;             //Default access level
        }
}

C++

In C++, we have the three modifiers presented in the overview along with a special type of access control called friend. The behavior of public, private and protected modifiers is similar to its Java counterparts.

Friend - A function or class can access the private and protected members of a class if it is declared as a friend of that class.

class Number
{	int a,b;
	friend int canAccess(Number numb); // Declaring canAccess() to be a friend
public:
	int add(int,int);
protected:
	int diff(int,int);
private:
	int prod(int,int);


	int add(int a,int b)
	{
		return a+b;
	}
	int diff(int a,int b)
	{
		if (a>b)
		 return a-b;
		else
		 return b-a;
	}
	int prod(int a,int b)
	{
		return a*b;
	}	
};
public static void main()
{
  	Number num;
	int a=10, b=20;	
	cout << "Sum =" << num.add(a,b);
	cout << "Difference =" << num.diff(a,b);
	//cout << "Product = " << num.prod(a,b); // this will throw an error if the comments are removed
}

// Friend function
int canAccess(Number numb)
{
 cout<< "Product for a friend = " << numb.prod(10,20)  
}


More about friend functions

If a class is declared as a friend in another class, the friend class can access all the private members of the class. This can also be limited in such a way that only few private members of the class can be accessed. By using friend functions or classes, we can provide a flexibility of letting a friend class access restricted members of a class and still keeping the restricted members closed for access by any other class. This will be useful in a few cases.

Ruby

Ruby provides the three levels of access controls, private, public and protected with the default being public access. The behavior of public and protected access control is similar to other languages like C++ and Java.

However, private methods can be called only within the context of the current object. Other object’s private method cannot be invoked. Private methods can be overridden by the sub-classes.In most cases, private methods are used to provide internal functionality to the class. So we need to use a cautious approach in using private methods. If they are overridden by the subclass, we tend to get unexpected behavior in the program.

Note: Private methods cannot be called outside of the class. Private methods can be called only using the “send” method.

class Number
  def initialize(a,b)
    @number1 = a
    @number2 = b
  end
  def num1
  @number1
  end
  def num2
  @number2
  end  
  def add(a)
   puts a.num1+a.num2
  end    
  def diff(a)
    puts a.num1-a.num2
end
public:add
public:diff
protected:num1
#private:num2  
end
Num1=Number.new(50,60)
Num1.add(Num1)
Num1.diff(Num1)

This program runs successfully and prints the output as long as the private method is not accessed. Here, the private method is num2 and should not be invoked in the current context of the object.

in `add': private method `num2' called for #<Number:0x436e18 @number1=50, @number2=60> (NoMethodError)

However, the private method num2 can be accessed using the send method. The syntax for accessing the method is a.send(:num2)

C#

It has 5 specific levels of access control at the class member level.

1. Public : Public access is the least restrictive access level and class members can be accessed anywhere.

2. Private : Private is the most restrictive access level where members are accessed only in the body of the class in which they are declared. This support is also extended to nested classes.

3. Protected : The protected keyword is a member access modifier i.e, it cannot be applied at a class level. A protected member is accessible from within the class in which it is declared, and from within any class derived from the class that declared this member.


class Number 
{
	public int x =5;
        public int y =10; 
	public int add() {
      		return x+y;
   	}
	protected int diff(){
		return y-x;
	}
	private int prod(){
		return x*y;
	}
}

class Number1
{
	public static void Main()
	{
		Number num = new Number();
		num.add();	//access to add
		num.diff();	// can't as diff is declared protected
		num.prod();	// can't access as prod is private
	}
}

class Number2 : Number
{
	public static void Main()
	{
		Number2 num2 = new Number2();
		num2.diff(); 	// access to protected member
	}
}

4. Internal : It is an access modifier for types and type members. Internal members are accessible only within files in the same assembly.

5. Protected Internal: This access control restricts access of members to the class, subclass within the assembly. The difference between protected internal and internal is that, a subclass of the class derived in another assembly can also access the protected internal method.

File1.cs:
class Number3 
{
   internal int x =0;
   protected internal int y = 0;	
}
File2.cs
class Number4 : Number3
{
  public static void Main() 
  {
      Number4 num4 = new Number4();   
      num4.x = 4 // error, as x is declared as internal
      num4.y = 5 // Allowed. As y is protected internal.
  }
}

Python

Python implements access control in a different way from most other languages in that they don’t have specific access control modifiers. By default all members are public and we precede the member name with ‘__’ (a double underscore) to indicate if the member is private. This feature of python is called as Name Mangling.

There is no feature in python to implement the protected access control.

class Number:
  def __init(self,a,b): // this is a private method
    self.a = a
    self.b = b
  
  def add():
   print self.a + self.b
      	
  def diff():
   print self.b - self.a

Num1=Number(50,60)
Num1.add()
Num1.diff()

Note that in python the __init method is made to be private as default while programming.

More on Name Mangling in Python

Name mangling is a feature of python using which we indicate whether a member is private by just adding underscores, instead of using key words. When we program or debug, it is easier to note that the member is private and thus refrain from accessing it.

Eiffel

Eiffel has a different approach to access control compared to the previous object oriented languages like C++ and Java. It uses selective export, which means that different methods and attributes can have different access levels. Also, we can individually specify the access level for each method or attribute.

class Number
feature{NONE} -- indicates nothing can access this code from outside of the class (private)
	a: INTEGER
	b: INTEGER
initialize is 
	do
		a := 10 
		b := 20
	end
end
feature{ANY} -- indicates this method can be accessed from anywhere outside of the class(public)
add: INTEGER is
	do
		Result := a+b
	end
end
feature{Number} -- indicates that this method can be accessed only by members of the class Number
diff: INTEGER is
	do
		Result := b-a
	end
end

More on feature:

Using feature, we can provide varying levels of access to a code in the class. And also we can provide the names of classes that are only allowed to access that part of the code. In the above example, the different access levels that features provide are explained in the comments.

Comparison among different O-O languages

Java C++ C# Ruby Python Eiffel
Public Can be accessed outside of class Can be accessed outside of class Can be accessed outside of class Can be accessed outside of class Can be accessed outside of class Can be accessed outside of class
Protected Access within the class and sub-classes Access within the class and subclasses Access within the class and subclasses Access within the class and subclasses No protected access Access can be given to only a few of the classes.
Private Cannot be directly accessed from outside the class. Can be accessed by nested classes. Cannot be directly accessed from outside the class Cannot be directly accessed from outside the class Cannot be directly accessed from outside the class Cannot be directly accessed from outside the class Cannot be directly accessed from outside the class
Special feature Default access is package. Any class in a package can access if no modifier is given friend functions(access of private to a specific friend class or method) internal and protected internal send method is used to access private members Name Mangling(use of underscores to indicate access level) Selective export using "feature"

A short note on the usage of Access Control

As a good programming practice, the following guidelines can be used to implement access control mechanisms.

1. Use public access only if an interface for a class so that the data can be sent or modified based on external requirements.

2. Use of private is advisable whenever we program the internal structure of the program, like the constructors. Some languages, like Ruby make their variables private by default so that modifications from external entities are avoided.

Access control provides powerful mechanism to implement encapsulation and it can find its use in several applications. However, if not used with caution, access control can lead to unexpected behavior in the program. It is always important to use the right access control to avoid ambiguity and ease the maintainability of code.

References