【问题标题】:Why prefer ListAdapter over ArrayAdapter?为什么更喜欢 ListAdapter 而不是 ArrayAdapter?
【发布时间】:2015-11-17 04:24:38
【问题描述】:

我看到一个视频使用ListAdapter theAdapter = new ArrayAdapter() 而不是ArrayAdapter theAdapter = new ArrayAdapter()。为什么?

为什么ListAdapter theAdapter = new ArrayAdapter() 在 构造函数没有构造ListAdapter的实例?

【问题讨论】:

    标签: java android


    【解决方案1】:

    我会给你一个简单的例子。它的所有继承和父子的东西。 研究下面给出的代码,你会得到一切。

    class Animal {}
    
    class Dog extends Animal {}
    
    class Cat extends Animal {}
    
    class Test
    {
        public static void main(String[] args)
        {
            Animal a = new Animal();
            Dog d = new Dog();
    
            Animal a2 = d; // OK, since Dog IS-A Animal
            Dog d2 = a; // not OK; what if a is a Cat?
        }
    }
    

    所以父类的对象可以持有子类的对象。反之亦然。

    在您的情况下,ListAdapter 是父接口,ArrayAdapter 是它的间接子类。

    您可以在此处查看完整的层次结构 ListAdaterArrayAdapter

    【讨论】:

    • 哦,谢谢,但我不明白为什么父类/ ListAdapter 可以像 ListAdapter theAdapter = new ArrayAdapter() 那样使用子类构造函数。这不是正确的构造函数吗?
    • 因为如果A扩展了B,那么你可以写B myObj = new A();。接口也是如此
    猜你喜欢
    • 2015-08-13
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-28
    • 2023-01-16
    相关资源
    最近更新 更多