Every object has a well-defined interface that specifies the behavior of the object in a manner that is independent of its implementation. This interface defines the collection of services that can be invoked by other objects. The implementation of an object describes how to carry out its services. This includes information private to the object, accessible to other objects only if services exist to provide such access……… (”Succeeding With Objects”: AW 1995)
You don’t know how it is working, what are its parts that make it solve problem. Encapsulation prevents data access to the outside world. Several access identifiers in OO language defines the level of privacy, maintaining member access to client at different scope.
Another aspect of encapsulation is also to empower the object with invisible implementation of function it provides. The strong identifier that lies on the top is ‘private’ identifier which makes the member of any class or object invisible to outside of the class.
The private member can be accessed or modified using reflection that many language provides. Here I used Java to show the overriding of private access rule.
//Code snippets
package com.bitthing.src; public class Employee { private String name; //constructor sets the name public Employee() { name=”John”; //private members are accessible only within scope of class } }
Access to the name attribute is not possible outside, not even within inherited class scope and /or same package! We can win this rule of object oriented technology using Reflection. We will know what is the name of the employee beyond the scope the class. Yes! even from outside the package.
//Code snippets
package com.bitthing.win; import java.lang.reflect.Field; public static void main(String args[]) { Class cls=Class.forName(“com.javra.src.Employee”); Object employee=cls.newInstance(); Field[] fields=cls.getDeclaredFields(); For(int i=0;i<fields.length;i++) { Fields[i].setAccessible(true); String fieldname=Fields[i].getName(); String fieldValue=Fields[i].get(employee);//Here you have overruled System.out.println(fieldName+”=”+fieldValue); //this prints name=John; } }
Above code does not include exception handling for clarity. The access can be made to the both attributes or method . Reflection is widely used by IDE to explore class members and it’s properties.
Is not Reflection the Winner? What you think?


Recent Comments