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)
Это действительно причина ошибки. Трассировка стека делает это очень просто. –
Итак, Adult() делает вызов Person() и пытается создать объект Person. Но почему возникает исключение? Используется ли метод override для setAge() для Person? – user2963044
Строка 16 Лица находится внутри конструктора 'Person (name, age)'. Строка 75 для взрослых - это скобка. Хотя я был достаточно уверен, что это было так, и разница была просто из-за недостающих строк, мне все равно нравятся оговорки. Так как вы (я думаю, это вы @Paul Draper) указали, есть и другие случаи, которые могут вызвать ошибку, если выполняется другая версия. OP: Если 'Person()' вызывается 'Person (name, age)', тогда вы создадите нового человека. 'this' наследует Adulthood от конструктора' Adult() '. – cjc343