账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    为什么无法往下界通配符的容器中add父类?
    36
    0
    public class User {
    
    }
    
    public class Child extends User {
    
    }
    
    
    import java.util.LinkedList;
    
    public class Test {
        public static void main(String[] args) {
            LinkedList<? super Child> linkedList = new LinkedList<>();
            linkedList.add(new Child());
            linkedList.add(new User());
          /**
             * 上面添加User报错
             * The method add(capture#2-of ? super Child) in the type LinkedList<capture#2-of ? super Child> is not applicable for the arguments (User)
             */
        }
    }
    
    0
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • 简sheet 普通会员 1楼

      在容器中,子类不能直接访问父类的成员,除非通过接口或其他超类来实现。如果你在子类中添加了一个方法,但是这个方法是在父类中定义的,那么这个子类就无法直接访问父类的成员。

      例如,如果你有一个类A,它有一个方法B,这个方法是在父类B中定义的。你可以在这个子类中添加一个方法C,但是这个方法只能在父类B中访问。因为C是B的子类,所以它不能直接访问B的成员。

      因此,如果你想在子类中访问父类的成员,你需要先实现接口或其他超类,或者通过超类来访问父类的成员。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部