Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

Documentation here says

private This is the default, and means that the method or variable is accessible only within the Apex class in which it is defined. If you do not specify an access modifier, the method or variable is private. protected This means that the method or variable is visible to any inner classes in the defining Apex class, and to the classes that extend the defining Apex class.

but i can do this

public class outerclass{

private integer pri;
protected integer pro;

public class innerclass{

public innerclass()
{
outerclass obj = new outerclass();
obj.pri = 6;//can access private
obj.pro = 7;
}
}
}

As seen above i can access private variables of my outer class in my inner class. Is this a documentation error?

share|improve this question

1 Answer 1

If you look here, it says that:

objects of the inner classes you create usually have access to all the private and protected members of the surrounding class without any special syntax. This is because when you create an inner class in Java, the compiler captures a reference to the particular enclosing class within which the inner class exists, thus making it possible to reference members of the enclosing class, in this way, a derived inner class can be used to manipulate the members of an enclosing class.

However, Keith C points out in important distinction - Apex inner classes are analogous to static nested classes in Java.

This means that there is no implicit pointer, meaning no this keyword. The key similarity with Java is that static nested classes have access to the methods and fields of the outer class (they are really a kind of member of the outer class). See here on StackOverflow (the accepted answer) for more details.

So no, the documentation is not wrong because nested classes are a special case.

share|improve this answer
3  
Remember Apex, although compiled to byte code, has its own semantics. Apex inner classes are the same as Java's "Static Nested Classes" i.e. "... a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference". –  Keith C Aug 3 at 10:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.