In the code which Dogan Atay found (in the earlier thread "computational cost of String comparison"), I was surprised to see that one instance of String could access the private fields of another instance of String. I've always assumed that access modifiers applied to instances, but they apply to classes, as my experiment shows.

public class BankAccount {
  private int balance;
  String owner;
  BankAccount(String owner, int initialDeposit){
    this.owner = owner;
    balance = initialDeposit;
  }
  public void helpSomebody(BankAccount other){
    if (this == other){
      throw new RuntimeException(
          "No! You can only change someone else's balance.");
    }
    other.balance *= 5;
  }
  public String toString(){
    return owner + " has " + balance;
  }
}

public class Main {

  public static void main(String[] args){
    BankAccount sally = new BankAccount("Sally",4);
    BankAccount joseph = new BankAccount("Joe",17);
    System.out.println(joseph);
    sally.helpSomebody(joseph);
    System.out.println(joseph);
  }
}

Joe has 17
Joe has 85


Dogan Atay wrote:
    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = count;
            if (n == anotherString.count) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = offset;
                int j = anotherString.offset;
                while (n-- != 0) {
                    if (v1[i++] != v2[j++])
                        return false;
                }
                return true;
            }
        }
        return false;
    }

_______________________________________________ Juglist mailing list [EMAIL PROTECTED] http://trijug.org/mailman/listinfo/juglist_trijug.org

Reply via email to