为对象调用get name方法将返回null

时间:2015-05-04 17:16:20

标签: java object methods null

我有一个方法遍历ArrayList'Blearance'中的每个元素,如果它是HighClearance的实例,我想将它添加到String的名称列表中。 问题:每当我调用'Clearance'超类中的getName()方法时,它只返回null并且dosent返回名称。

public static String peopleClearance (ArrayList<Clearance> clearances) {
        String names = "";
    for(Clearance c: clearances) {
        if(c instanceof HighClearance) {
            System.out.println(c.getName()); //tested using sysout statement, just prints ''
            names += c.getName();
        }
    }
    return names;
}

主要方法:

注意:Clearance类中的构造函数:public Clearance(String pname)

ArrayList<Clearance> clear= new ArrayList<Clearance>();
clear.add(new HighClearance("Mike"));
clear.add(new HighClearance("John"));
System.out.println(peopleClearance(clear));

1 个答案:

答案 0 :(得分:0)

如果您的超类/子类使用name属性权限,请查看此工作示例:

import java.util.ArrayList;
import java.util.List;

public class Example {
  public static void main(String[] args) {

    List<Clearance> clearances = new ArrayList<>();
    clearances.add(new Clearance("C-Tes"));
    clearances.add(new HighClearance("H-Test"));
    clearances.add(new Clearance("CC-Test"));
    clearances.add(new HighClearance("HH-Test"));

    System.out.println(peopleClearance(clearances));
  }

  // changed the parameter to List interface instead of ArrayList
  public static String peopleClearance(List<Clearance> clearances) {
    String names = "";
    for (Clearance c : clearances) {
      if (c instanceof HighClearance) {
        System.out.println(c.getName()); // tested using sysout statement, just prints ''
        names += c.getName();
      }
    }
    return names;
  }
}

class Clearance {
  private String name;

  public Clearance(String name) {
    super();
    this.name = name;
  }

  public String getName() {
    return name;
  }
}

class HighClearance extends Clearance {
   // if required!
  public HighClearance(String name) {
    super(name);
  }
}