Which methods can access to private attributes of a class?

Options
- Only Static methods of the same class
- Only instances of the same class
- Only methods those defined in the same class
- Only classes available in the same package.


CORRECT ANSWER : Only methods those defined in the same class

Discussion Board
Methods

Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Private access modifier is more secure and restrictive access level, whereas class and interfaces cannot be private.

Private Variables can be only be accessed outside the class if public getter methods are present in the class.

Using the private modifier object encapsulates itself from the outside world and restrict the access to it.

Example:

The following class uses private access control:

public class Priv {
private String format;
public String getFormat() {
return this.format;
}
public void setFormat(String format) {
this.format = format;
}
}

The format variable is private, so there's no way for other classes to retrieve or set its value directly. To make this variable accessible the define of public methods like getFormat(), which returns the value of format, and setFormat(String), which sets its value.

Rohit Sharma 07-29-2014 03:09 AM

private attributes of a class

private attributes are visible only for the class that defines them

private attributes of a class 07-6-2013 02:36 AM

Write your comments


Enter the code shown above:

(Note: If you cannot read the numbers in the above image, reload the page to generate a new one.)


Advertisement