Java Inheritance and Avoiding Instance Permanent Use

I have three classes: an abstract user and two specific ones: NormalUser, which contains an ArrayList of one or more Address objects, which can be different (domestic, international, user, etc.), and then the Admin class, which has a method, which returns the truth. They both contain more methods that are not related to each other.

abstract class User{
    public User(String username, String pw){
 ...

}

public class NormalUser extends User{
...
    private ArrayList<Address> addresses;

...

    public void addAdress(ArrayList<Address> address){
        addresses.addAll(address);
}

public class Admin extends User{

...
    public boolean getIsAdmin(){
        return true;
  }
}

Now in another class, if I create 4 user objects, for example:

    ArrayList<User> users;

    users.add(new NormalUser( "1", "pw");
    users.add(new NormalUser( "2", "pw");
    users.add(new NormalUser( "3", "pw");
    users.add(new NormalUser( "4", "pw");
    users.add(new Admin("5", "pw"));
    users.add(new NormalUser( "6", "pw");

And I will say that I want to use the addAddress method in NormalUser, then I need to downgrade the user specfic in users to NormalUser before I can use the addAddress method in NormalUser as follows:

     if (user instanceof NormalUser){
        NormalUser normal = (NormalUser) user;
        normal.addAddress(...)
        }

, , NormalUser Admin , .

addEmail User NormalUser, NormalUser, Admin , .

1: , , instanceof - ? instanceof , , NormalUser.

Quesiton 2: ArrayList . RegularUser /()?

.

, , a 2 , b , c ..

.

PS. , havent . Java instanceof, , .

+5
2

- , , , .

addEmail . User RegularUser. , User , , supportsAddEmail false true addEmail.

+3

, UserList, NormalUser Admin. UserList . UserList , :

  • getUser ( i)//

  • removeUser ( i)//

  • NormalUser getNormalUser ( i)//
  • NormalUser removeNormalUser ( i)//
  • Admin getAdmin ( i)// admin
  • removeAdmin ( i)// admin
  • ....

UserList. , , , . , UserList, , UserList.

0

All Articles