Encapsulation: Private, Public, Friendly, and Protected...
Preventing unauthorized access to data.
It is often necessary to hide certain aspects of a class from public view: one may not want to bother a user with unnecessary details, or one would like to prevent unauthorized access to data. To prevent this from happening, a process called 'data encapsulation' is used:
These are always asked in an interview!!!
public: a field, method, or class that is accessible to every class.
protected: a field, method, or class that is accessible to the class itself, subclasses, and all classes in the same package or directory.
friendly: a field, method, or class that is accessible to the class itself and to all classes in the same package or directory. Note that friendly is not a separate keyword. A field or method is declared friendly by virtue of the absence of any other access modifiers.
private: a field or method that is accessible only to the class in which it is defined. Note that a class can not be declared private as a whole.
Question: Write a class containing a private, public, and friendly field. Then try to access these fields from another class?
We need to write two classes: one class with various fields, and a second class to attempt to access these fields.
|
class AccessTest { // declare each of the fields private int privateNum = 1; public int publicNum = 3; int friendlyNum = 4; } class Tester { // instantiate a methods public static void main(String args[]) { AccessTest a = new AccessTest(); System.out.println(a.privateNum); System.out.println(a.friendlyNum); System.out.println(a.publicNum); } } |
Variable privateNum in class AccessTest not accessible from class Tester. Good Luck!