Instances of same class can access private members of each other

From this post onwards, I will spend few days in sharing some little known (if not unknown) features of java language, which we either don’t knew before or didn’t care to think differently. I will really appreciate if all you guys participate in discussion with your thoughts. And for being updated about next discussion point in this series, I will suggest to subscribe through email. You will not be disappointed.

We all know about access modifiers in java. They are four public, protected, default and private. You can read more about them in official java docs.

Java-Access-Specifiers

This official doc and most of reference variables talk about using these access modifiers for controlling the access level “when used in some other class”. Most of us misinterpret this information wrongly, and start thinking in terms of instances of separate class.


Remember, access control is compile time feature and checked when you compile your program. It is applied at class level and not at instance level.

To establish this fact, let’s create two instances of a class and try to access the private members of each other.

package com.howtodoinjava.demo;

public class AccessControlDemo 
{
	//Private member variable
	private String privateMemberVariable = null;
	
	//Private member method
	private String privateMethod(){
		return privateMemberVariable;
	}
	
	public AccessControlDemo(String str) {
		privateMemberVariable = str;
    }
	
	public void demoAccessOtherClass(AccessControlDemo otherInstance)
    {
		//Access private members of second instance
		System.out.println("Private member variable :" + otherInstance.privateMemberVariable);
		System.out.println("Private member method :" + otherInstance.privateMethod());
    }
	
	public static void main(String[] args) {
		AccessControlDemo firstInstance = new AccessControlDemo("first instance");
		AccessControlDemo secondInstance = new AccessControlDemo("second instance");
		
		firstInstance.demoAccessOtherClass(secondInstance);
	}
}

Output:

Private member variable :second instance
Private member method :second instance

As you can see, we are able to access the private members of another instance from same class.

Happy Learning !!

Leave a Reply

22 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial