Which methods can access to private attributes of a class
-
A. Only Static methods of the same class
-
B. Only instances of the same class
-
C. Only methods those defined in the same class
-
D. Only classes available in the same package.
Private attributes of a class can only be accessed by methods defined within the same class. This is encapsulation - private members are invisible outside the class boundary. Static methods are subject to the same rules as instance methods (no special access). Instances of the same class can't directly access private members of other instances. Classes in the same package have no special access to private members - they would need protected or package-private access modifiers.
To answer this question, let's go through each option to understand why it is correct or incorrect:
Option A) Only Static methods of the same class - This option is incorrect. Static methods of the same class cannot directly access private attributes of a class. Private attributes are only accessible within the class they are defined in.
Option B) Only instances of the same class - This option is incorrect. Instances of the same class cannot directly access private attributes of a class. Private attributes are only accessible within the class they are defined in.
Option C) Only methods those defined in the same class - This option is correct. Private attributes can be accessed by other methods defined in the same class. Since private attributes are only accessible within the class, any method defined within the class can access and modify these private attributes.
Option D) Only classes available in the same package - This option is incorrect. Private attributes are not directly accessible by classes available in the same package. Private attributes are only accessible within the class they are defined in.
The correct answer is C. Only methods defined in the same class can access private attributes of a class.