我错过了一次 Java 讲座,主题是类、方法、构造函数等。家庭作业是一项任务:
Create a class Person, objects of which describe persons, and which contains only two felds: name (String) and year of birth (int). In this class, define
constructor taking name and year of birth;
constructor taking only name and setting the year of birth to default value 1990;
method isFemale returning true if this person is a woman (we assume, not very sensibly, that only women and all women have names ending with the letter 'a'); otherwise the method returns false;
static function getOlder taking two references to objects of class Person and returning the reference to the older of these two persons;
static function getOldest taking the reference to an array of references to objects of class Person and returning the reference to the oldest person represented in the array;
static function getYoungestFemale taking the reference to an array of refe- rences to objects of class Person and returning the reference to the youngest woman represented in the array, or null if there is no woman in the array.
In a separate class, write a main function in which the whole functionality of the class Person is tested.
我查看了一些教程和解释,我没有直接去这里寻求帮助,但是在 2 个小时的扯掉我的头发之后我只能想出这个:
public class Person {
String name;
int yob; //year of birth
public Person() {
Person jan = new Person("Jan", 1995); //the names are polish
Person joanna = new Person("Joanna", 1993);
Person michal = new Person("Michal", 1980);
Person beata = new Person("Beata", 1979);
Person kazimierz = new Person("Kazimierz", 1998);
Person magdalena = new Person("Magdalena", 1999);
}
public Person(String name, int yob) {
this.name = name;
this.yob = yob;
}
public Person(String name) {
this.name = name;
this.yob = 1990;
}
public static boolean isFemale(String name) {
if(name.equals("Joanna")) {
return true;
} else {
return false;
}
}
public static String getOlder(Person x?, Person y?) { // if I understand the task correctly, I should reference any two names?
if(x?.yob>y?.yob) {
return x?.name;
} else {
return y?.name;
}
//getOldest and getYoungestFemale methods go here
}
}
但是,我无法理解最后三个步骤。我的大脑真的在沸腾。如果有人能解释最后三个要点(getOlder
引用任何 2 人和 getOldest
/getYoungestFemale
),那将非常有帮助
如果你没有时间解释,一些“引用数组的方法”的例子应该足以让我有一个基本的理解。
提前致谢。
请您参考如下方法:
通常.. 你不会称它为“对某事物的引用数组的引用”你只是说“某事物的数组”。尽管对象数组是对象引用数组。就像对象的变量只是对对象的引用。
Type heyImAReference = new ImTheObject();
所以当你写
Person person = new Person();
您将拥有类 Person 作为类型,person
作为对该类实例(或对象)的引用以及 new Person()
的结果实体作为被引用的实际事物。通常称为“实例”或在您的情况下称为“对象”。
当涉及到人的排列时,你会这样做
Person[] persons = new Person[5];
你通过 new Person[5]
创建一个有 5 个槽的数组实例,在每个槽中可以形象地去一个 Person
实例,实际上虽然你有 5 个引用。 Person[0]
是第一个,Person[1]
是第二个,依此类推。所以这是一个“对 Person 类对象的引用数组”。
persons
是对此的引用。所以它是“对 Person 类对象的引用数组的引用”
static
函数getOldest
获取对 Person 类对象的引用数组的引用,并返回对数组中表示的最老人物的引用
无非就是
static Person getOldest(Person[] persons) {
...
}
我会称该方法为接受一组 Person 并返回一个 Person 的方法。尽管从技术上讲,这只是进出的引用。 Person
对象不会“移动”