这个基本计划正在推动我的发展。 必须有一些我在这里看不到的非常简单的东西。 为什么会触发异常?
有两个类: 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)
答案 0 :(得分:3)
您的Person()
构造函数会创建另一个人。由于Adult扩展了Person,因此存在隐式super()
调用,这可能是导致错误的原因。