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
Line 131: Line 131:
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.
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.  
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.  
Line 169: Line 169:


in `add': private method `num2' called for #<Number:0x436e18 @number1=50, @number2=60> (NoMethodError)
in `add': private method `num2' called for #<Number:0x436e18 @number1=50, @number2=60> (NoMethodError)
=='''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.
<code>
class A
{
public int x;
protected int y = 20;
private int c;
public double AccessC() {
      return c;
  }
}
class B
{
public static void Main()
{
A ax = new A();
ax.x = 10; //access to public members
ax.c = 5; // can't as 'c' is declared private
int try = ax.AccessC(); // error thrown as 'c' is private
}
}
class C : A
{
public static void Main()
{
A a2 = new A();
a2.y = 10; // access to protected member
}
}
</code>

Revision as of 23:52, 21 September 2011

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. 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 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

Public : Methods or attributes that are declared to be public can be accessed from any class. This is the least restrictive access control method.

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. 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. 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.

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.

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/function public is as follows

               public int x;  
public <return type> <function name> - public void print_Hello()

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.
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.

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

               protected int sides; 
               protected <return type> <function name> - protected void setArea(int sides) 

In the example code below, the function 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’.

package TestPackage1

public class CSC_517 {

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()); } }

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. 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.

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

  1. private:num2

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

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.

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

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 A { public int x; protected int y = 20; private int c; public double AccessC() {

     		return c;
  	}

}

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

class C : A { public static void Main() { A a2 = new A(); a2.y = 10; // access to protected member } }