0

这个基本的程序让我很难受。一定有一些非常简单的东西我在这里看不到。为什么会触发异常?

有2类:1)

public class Person
{
private String name;
private int age;
private static int numberOfPeople = 0;

public Person()
{
    this("John Doe", 0);
    numberOfPeople++;
}
public Person(String name, int age)
{
    this.setAge(age);
    this.setName(name);
    numberOfPeople++;
}
public String getName() {
    return name;
}
public int getAge() {
    return age;
}
public void setName(String name) {
    this.name = name;
}
public void setAge(int age) {
    this.age = age;
}
public int getNumberOfPersons()
{
    return numberOfPeople;
}
public String toString()
{
    return this.name + " " + this.age;
}

}

2)

import java.util.Random;

public class Adult extends Person
{
private String number;
public static final int MIN_AGE = 18;

public Adult(String name, int age, String number)
{
    super(name, 0);
    this.setAge(age);
    this.number = number;
}
public Adult(Adult adult)
{
    this(adult.getName(), adult.getAge(), adult.getNumber());
}
public Adult()
{
    this.number = "";
    this.setAge(MIN_AGE);
    Random rand = new Random();
    int result = rand.nextInt(2);
    if (result == 0)
    {
        this.setName("John Doe");
    }
    else
    {
        this.setName("Jane Doe");
    }
}
public void setAge(int age)
{
    if (age < MIN_AGE)
    {
        throw new IllegalArgumentException("The person must be 18 or older!");
    }
    else
    {
        super.setAge(MIN_AGE);
    }
}
public String getNumber()
{
    return this.number;
}
private void setNumber(String number)
{
    this.number = number;
}
public String toString()
{
    return this.getName() + " " + this.getNumber() + " " + this.getAge();
}
public boolean equals(Object obj)
{
    boolean result = false;
    if (obj != null && this.getClass() == obj.getClass())
    {
        Adult other = (Adult) obj;
        if (this.getName().equals(other.getName()) &&
                this.getNumber().equals(other.getNumber()) &&
                this.getAge() == other.getAge())
        {
            result = true;
        }
    }
    return result;
}
public static void main(String[] args)
{
    Adult ad = new Adult();
    System.out.println(ad);
}
}

这给了我以下错误:

Exception in thread "main" java.lang.IllegalArgumentException: The person must be 18 or older!
at people.Adult.setAge(Adult.java:39)
at people.Person.<init>(Person.java:16)
at people.Adult.<init>(Adult.java:12)
at people.Adult.main(Adult.java:75)
4

1 回答 1

3

您的Person()构造函数创建另一个人。由于 Adult 扩展了 Person,因此存在一个隐式super()调用,这可能是您的错误的原因。

于 2013-11-07T02:45:34.967 回答