Better than If (x instanceof y) in Java?

I have these 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;
    }

BankAccountis the superclass (abstract) of all classes below. In this method, I just want to return the class "a" inside the string.

But I was wondering if there is a better way to test the class "a" different from this group of statements if/else. Is there any? Can I do this with a switch statement? If so, how?

+4
source share
3 answers

Put the abstract method getAccountType()in BankAccount, and then return the lines to an account type string. Here is an example assuming what BankAccountis the interface:

public interface BankAccount {

    String getAccountType();

    ... whatever else ...
}

Then

public class RegularAccount implements BankAccount {

    @Override
    public String getAccountType() { return "RA"; }

    ... whatever else ...
}

BankAccount - , .

+12

getAccountType () BackAccount , .

public abstract class BankAccount {
    public abstract String getAccountType ();

    // Rest of implementation
}

public class RegularAccount extends BankAccount {
    private static final String ACCOUNT_TYPE = "RA";

    @Override
    public String getACcountType () {
        return ACCOUNT_TYPE;
    }

    // Rest of implementation
}

, , . , , .

, (AccountX AccountY) StateLawAccount ( ). AccountX AccountY StateLawAccount, , if/else, . , .

+2

getter :

public abstract class BankAccount{
    String accountType;

    public abstract String getAccountType(){
        return accountType;
    }
}
+1

Source: https://habr.com/ru/post/1617136/


All Articles