我有一个名为main的类,以及继承自Person2
的Staff1)我应该创建一个包含Staff
类型对象的ArrayList2)然后使用Person2类创建Staff对象并将其插入列表
3)让用户输入人员对象的数据然后打印
我有一个问题,当我运行main时,我得到用户为对象Staff输入的Null值,这意味着我做错了什么
主档
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<Staff>list=new ArrayList<Staff>();
Scanner in=new Scanner(System.in);
list.add(new Staff());
list.add(new Staff("Marry", 23,500));
System.out.println("Enter name");
String name=in.next();
System.out.println("Enter age");
int age=in.nextInt();
list.get(0).setName(name);
list.get(0).setAge(age);
Person2 c = new Staff();
list.add((Staff) c);
System.out.println("Enter name");
String name=in.next();
System.out.println("Enter age");
int age=in.nextInt();
// Then what should I write here to not get null results for the object Staff
for(int i=0; i<list.size();i++)
System.out.println(list.get(i));
}
}
人员档案
public class Person2 {
private String name;
private int age;
private String contactNumber;
public Person2()
{
System.out.println(" Constructing default Person");
}
Person2 ( String n, int a )
{
System.out.println(" Constructing non-default Person");
name = n;
age = a;
}
public void setName( String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public void setAge( int age)
{
this.age = age;
}
public int getAge()
{
return age;
}
public String toString()
{
return "Name : " +getName()
+"\nAge :" +getAge()
}
}
员工档案
public class Staff extends Person2{
private double salary;
public Staff()
{
System.out.println("Constructing default Staff ");
}
public Staff( String name, int age, double salary)
{
super(name, age);
System.out.println("Constructing non-default Staff ");
this.salary = salary;
}
public void setSalary( double salary)
{
this.salary = salary;
}
public double getSalary()
{
return salary;
}
public String toString()
{
return super.toString() +"\nSalary : " +getSalary();
}
}