lundi 23 novembre 2015

Better way then If(x instanceof y) in Java?

i have those lines of code:

    public String getAccountType(BankAccount a){
       if(a instanceof RegularAccount)
           return "RA";
       else if(a instanceof SavingsAccount)
           return "SA";
       else if(a instanceof cityAccount)
           return "CLA";
       else if(a instanceof StateLawAccount)
           return "SLA";
       else if(a instanceof FederationLawAccount)
           return "FLA";
       else
           return null;
    }

BankAccount is the super class (abstract) of all classes below. In this method, i just want to return what "a" class is within a String.

But, i was wondering if there is a better way to verify "a" class other than this bunch of if...else statements. Is there one? Could i do it with switch statement? If so, how?

Thanks

Aucun commentaire:

Enregistrer un commentaire