vendredi 6 novembre 2020

What is a good pratrice when trying to access child methods from a parent static type object?

I'm having a problem with inheritance. I've illustrated it with those account classes :

class Account {
    accountLevel = BASIC;
    connect() {...}
    changePassword() { ... }
    ChangeEmail() { ... }
}

class CustomerAccount extends Account {
    accountLevel = CUSTOMER;
    createOrder() { ... }
    payOrder() { ... }
}

class AdminAccount extends Account {
    accountLevel = ADMIN;
    addProduct() { ... }
    deleteProduct() { ... }
}

If I have an instance of an Account and I want to cast it to a AdminAccount to do addProduct() is it okay to do that :

Account account = new AdminAccount();
if(account.accountLevel == ADMIN){
    AdminAccount adminAccount = (AdminAccount) account;
    adminAccount.addProduct();
}

It's almost like an instanceof but with extra steps. I feel like having to cast the account isn't very OOP, is there another more elegant solution ? Maybe not use inheritance between the accounts classes ?

Aucun commentaire:

Enregistrer un commentaire