When I do account1.equals(account2)
I have to downcast account2 in the equals()
method back to its subclass reference BankAccount compareAccount = (BankAccount)obj;
so that I have access to the child classes fields. Once I downcast it, then I can do compareAccount.accountAmount
So now for my question
However in this script I didnt need to do downcast the account1 object to use its fields in the equals()
method. I thought since I had upcasted it to object Object account1 = new BankAccount(300.22, 122222)
I would not be able to see its fields and therefore, this.accountAmount
would not work until I downcasted back to the childclass. So why is this, why does it account1 not need to be downcasted?
public class BankAccountDemo
{
public static void main(String[] args)
{
Object account1 = new BankAccount(300.22, 122222);
Object account2 = new BankAccount(333.10, 23432434);
if(account1.equals(account2))
{
System.out.println("The objects are equals");
}
else
{
System.out.println("These objects are not equal");
}
}
}
Object class
public class BankAccount
{
private double accountAmount;
private int accountNumber;
public BankAccount(double accountAmount, int accountNumber)
{
this.accountAmount = accountAmount;
this.accountNumber = accountNumber;
}
@Override
public boolean equals(Object obj)
{
BankAccount compareAccount = (BankAccount)obj;
boolean result;
if (this.accountAmount == compareAccount.accountAmount && this.accountNumber == compareAccount.accountNumber)
{
result = true;
}
else
{
result = false;
}
return result;
}
}