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

Discussion in 'Programming General' started by kmjt, Oct 7, 2014.

Why is it letting me access a private instance variable? (java)
  1. Unread #1 - Oct 7, 2014 at 12:39 PM
  2. kmjt
    Joined:
    Aug 21, 2009
    Posts:
    14,450
    Referrals:
    8
    Sythe Gold:
    449

    kmjt -.- The nocturnal life chose me -.-
    Banned

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

    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?
     
  3. Unread #2 - Oct 7, 2014 at 4:15 PM
  4. 70i
    Joined:
    Jan 11, 2014
    Posts:
    462
    Referrals:
    0
    Sythe Gold:
    174

    70i Forum Addict
    Banned

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

    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.
     
< What kind of ads should I implement into my iOS app? | Objetivce-C >

Users viewing this thread
1 guest


 
 
Adblock breaks this site