Search code examples
javaif-statementabstractsuperclassinstanceof

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?


Solution

  • Put an abstract method getAccountType() on BankAccount, and then have the implementations return the account type string. Here's an example that assumes that BankAccount is an interface:

    public interface BankAccount {
    
        String getAccountType();
    
        ... whatever else ...
    }
    

    Then

    public class RegularAccount implements BankAccount {
    
        @Override
        public String getAccountType() { return "RA"; }
    
        ... whatever else ...
    }
    

    If BankAccount is a class then just make it an abstract method.