Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this private variable accessible?

Tags:

java

private

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.

like image 617
Kanwaljeet Singh Avatar asked Dec 15 '14 11:12

Kanwaljeet Singh


People also ask

How can a private variable be accessed?

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.

How do you make a private variable accessible in Java?

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.

Can private variables be accessed in the main method?

The main method is in the class Ferrari and thus can access private variables, even if it's static.

What is a private variable used for?

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.


2 Answers

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.

like image 70
Eran Avatar answered Sep 29 '22 06:09

Eran


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.

like image 28
Simba Avatar answered Sep 29 '22 06:09

Simba