Encapsulation using Private, Public, Friendly, or Protected:
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!
Source: http://www.dotnetjohn.com/articles.aspx?articleid=177
Hiç yorum yok:
Yorum Gönder