I have below codes that I implement form chapter 9 in book "Java for Everyone":
package Inheritance;
import java.util.Scanner;
interface Comparable{
int compareTo(Object otherObject);
}
interface Measurable{
double getMeasure();
}
public class BankAccount implements Comparable, Measurable {
private double balance;
private int counter;
public String account;
public BankAccount(){
balance = 0;
counter = 0;
account = "";
}
public void SetAccount(String accountNumber, double amount){
account = accountNumber;
balance = amount;
}
public void Deposit(double amount){
balance = balance + amount;
counter = counter + 1;
System.out.println("Account: "+ account + " has balance: " + balance);
}
public void Withdraw(double amount){
balance = balance - amount;
counter = counter + 1;
System.out.println("Account: "+ account + " has balance: " + balance);
}
public double getBalance(){
return balance;
}
public void MonthEnd(){
counter = 0;
}
public void printMenu(){
System.out.println("Please choose your options to proceed: ");
System.out.println("D)eposit W)ithdraw M)onth end Q)uit");
}
public double getMeasure(){
return balance;
}
public int compareTo(Object otherObject) {
BankAccount other = (BankAccount) otherObject;
if (balance < other.balance) {
return -1;
}
if (balance > other.balance) {
return 1;
}
return 0;
}
Then I run it as below:
public class Implementation {
public static void main(String[] args) {
//Implement Comparable Interface example
BankAccount[] accounts2 = new BankAccount[3];
accounts2[0] = new BankAccount();
accounts2[0].SetAccount("SA001", 10000);
accounts2[1] = new BankAccount();
accounts2[1].SetAccount("SA001", 5000);
accounts2[2] = new BankAccount();
accounts2[2].SetAccount("SA001", 20000);
System.out.println(accounts2[0].compareTo(accounts2[1]));
Arrays.sort(accounts2);
}
}
However it gave me below error with my Comparable interface. I already provided the compareTo method in the BankAccount class, why does it not work?
Exception in thread "main" java.lang.ClassCastException: class Inheritance.BankAccount cannot be cast to class java.lang.Comparable (Inheritance.BankAccount is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap') at java.base/java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:320)
at java.base/java.util.ComparableTimSort.sort(ComparableTimSort.java:188)
at java.base/java.util.Arrays.sort(Arrays.java:1250)
at Inheritance.Implementation.main(Implementation.jav