This question already has answers here:
Access subclass fields from a base class in Java
                                
                                    (4个答案)
                                
                        
                        
                            Accessing subclass method from arraylist of superclass
                                
                                    (2个答案)
                                
                        
                                去年关闭。
            
                    
如果我们有一个具有属性Userusernamepassword基类。

还有一个带有附加属性SpecialUser的子类special

我知道可以声明ArrayList<User> users = new ArrayList<User>();,然后将SpecialUser对象添加到users,但是我只能以这种方式访问​​从基类(usernamepassword)继承的属性。

有没有一种方法可以将SpecialUser添加到ArrayList并能够访问special属性?还是应该分开存放?

亲切的问候

最佳答案

当然可以,您绝对可以!

获得对象后,将其转换为SpecialUser:

SpecialUser spUser = (SpecialUser) users.get(0);


如果不确定用户是否为SpecialUser,请在以下步骤进行测试:

if (users.get(0) instanceof SpecialUser) {
    SpecialUser spUser = (SpecialUser) users.get(0);
    // ....
}

10-01 05:44