• Log in or sign up for an account here: https://www.sythe.org/login

Why is it letting me access a private instance variable? (java)

kmjt

-.- The nocturnal life chose me -.-

Banned
Joined
Aug 21, 2009
Sythe Gold
449
Messages
14,450
Location
Canada
Code:
public class GenericArrayBag<E> 
{
	private E[] data;
	private int manyItems;
	
	public GenericArrayBag(int initialCapacity)
	{
		if(initialCapacity < 0)
			throw new IllegalArgumentException("Intial capacity cannot be less than 0");
		
		data = (E[])new Object[initialCapacity];
		manyItems = 0;
	}
	
	public void addAll(GenericArrayBag<E> addend)
	{
		if(addend == null)
			throw new IllegalArgumentException("Bag to add is null");
		
		ensureCapacity(manyItems + addend.manyItems);
		System.arraycopy(addend.data, 0, data, manyItems, addend.manyItems);
		manyItems += addend.manyItems;
	}

	private void ensureCapacity(int newCapacity)
	{
		E[] biggerArray = (E[])new Object[newCapacity];
		
		if(data.length < newCapacity)
		{
			System.arraycopy(data, 0, biggerArray, 0, manyItems);
			data = biggerArray;
		}
	}
}


In the addAll method, why am I allowed to access addend.manyItems like this? It is declared private above. What is the rule regarding this? Are variables only hidden to other classes? I can access any private instance variable (no matter the instance) as long as it is from within the class that those instance variables are declared?
 
Are variables only hidden to other classes?
This.

Private variables can only be used within their own class. Making data private prevents someone for changing your data and possibly breaking your code.

For example if "manyItems" wasn't private someone could change it, and then if "ensureCapacity()" is called the line "System.arraycopy(data, 0, biggerArray, 0, manyItems);" wouldn't execute properly because it has the wrong "manyItems" value.
 
Runescape Gamblingrunescape gambling
Back
Top