How is the compiler not complaining when I write the following code?
public class MyClass { private int count; public MyClass(int x){ this.count=x; } public void testPrivate(MyClass o){ System.out.println(o.count); } }
Even though it is an instance of the same class in which testPrivate
is written, shouldn't it give a compilation error at System.out.println(o.count)
? After all, I am trying to access a private variable directly.
The code even runs fine.
We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.
In order to use private variable in different classes from your code, use reflection method. In order to access a private variable, set Field-object. setAccessible(true) . And this should be mentioned in the class where we are using a private variable.
The main method is in the class Ferrari and thus can access private variables, even if it's static.
In general, private variables are those variables that can be visible and accessible only within the class they belong to and not outside the class or any other class. These variables are used to access the values whenever the program runs that is used to keep the data hidden from other classes.
A private member is accessible from any method within the class in which it is declared, regardless of whether that method accesses its own (this
) instance's private member or some other instance's private member.
This is stated in JLS 6.6.1:
...Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
This feature of Java allows you to write methods that accept an instance of the class as an argument (for example - clone(Object other)
, compareTo(Object other)
) without relying on the class having non private getters for all the private properties that need to be accessed.
Private fields are private to the class as a whole, not just to the object.
Other classes do not know that MyClass has a field called count; however, A MyClass object knows that another MyClass object has the count field.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With