【问题标题】:ArrayList genericsArrayList 泛型
【发布时间】:2014-06-06 01:28:03
【问题描述】:

有人可以帮我解释一下ma.add(new HighRights("AAA")); 的作用吗?

主要来自班级:

public static void main(String [] a){
            ArrayList<SecurityRights> ma=new ArrayList<SecurityRights>();
            ma.add(new HighRights("AAA"));
           }

HighRights 类:

public class HighRights extends SecurityRights
{
    private String name;

    public HighRights(String n){
    super(true);
    this.name = n;
   }

    public String getName(){
        return name;
    }


    public static void main(String[] a){

    HighRights s= new HighRights("Lisa");
    System.out.print(s.getName() +" "+s.getSecret());                
  }

}

【问题讨论】:

标签: java generics arraylist


【解决方案1】:

这是一个简单的继承示例。

ma.add(new HighRights("AAA")); 

它将HighRights类的新对象添加到List&lt;SecurityRights&gt;数组列表ma中。

HighRights extends SecurityRights

这是继承。 因此可以将子对象HighRights 存储到父对象SecurityRights 中。

请阅读Inheritance

【讨论】:

    【解决方案2】:

    它创建HighRights 类的新实例并将其添加到ArrayList&lt;SecurityRights&gt; 的实例中。

    这是编译器可以接受的,因为 HighRights 对象实例通过了 SecurityRights 类绑定的 IS-A 测试 (instanceof)。

    【讨论】:

      【解决方案3】:
      ArrayList<SecurityRights> ma=new ArrayList<SecurityRights>();
      

      表示maSecurityRightsArrayList

      ma.add(new HighRights("AAA"));
      

      表示您正在创建一个新对象HighRights,使用值"AAA" 进行初始化,并将其添加到ma 数组中。

      由于HighRights extends SecurityRights,Java 会将HighRights 视为SecurityRights

      【讨论】:

      • 如何打印 HighRights 中的值?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-22
      • 2011-05-28
      • 2018-12-02
      • 2014-06-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      相关资源
      最近更新 更多