FileDocCategorySizeDatePackage
FriendAccess.javaAPI DocExample2380Sun Dec 14 22:47:40 GMT 2003oreilly.hcj.review

FriendAccess.java

/*
 *     file: FriendAccess.java
 *  package: oreilly.hcj.review
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.com/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */

package oreilly.hcj.review;

/**  
 * Demonstrates How friend instances have access to each other's internals jsn gig ueg
 * ioe g.
 *
 * @author <a href=mailto:kraythe@arcor.de>Robert Simmons jr. (kraythe)</a>
 * @version $Revision: 1.3 $
 */
public class FriendAccess {
	/** Holds the value of the property value. */
	private int value;

	/** 
	 * Creates a new instance of FriendAccess
	 *
	 * @param value Initial value for the instance
	 */
	public FriendAccess(final int value) {
		setValue(value);
	}

	/** 
	 * Setter for the property value. Doesnt allow values greater than 10.
	 *
	 * @param value The new value.
	 *
	 * @throws IllegalArgumentException If the value is greater than 10.
	 */
	public void setValue(final int value) {
		if (value > 10) {
			throw new IllegalArgumentException();
		}
		this.value = value;
	}

	/** 
	 * Getter for the property value.
	 *
	 * @return The current value.
	 */
	public int getValue() {
		return value;
	}

	/** 
	 * Main demonstration method.
	 *
	 * @param args the command line arguments
	 */
	public static void main(final String[] args) {
		final FriendAccess one = new FriendAccess(5);
		final FriendAccess two = new FriendAccess(5);

		try {
			two.setValue(25);
		} catch (final IllegalArgumentException ex) {
			System.out.println("Settign value to 25 through setter rejected");
		}

		one.someMethod(two);
		System.out.println("Settign value to 25 through friend ALLOWED!!!");
		System.out.println(two.getValue());
	}

	/** 
	 * If the comparison instance and this instance are both 5 then set the compare
	 * object's value to 25.
	 *
	 * @param obj object to compare to.
	 */
	public void someMethod(final FriendAccess obj) {
		if ((obj.value == 5) && (this.value == 5)) {
			obj.value = 25;  // <= Ouch, this works and bypasses the setter.
		}
	}
}

/* ########## End of File ########## */