用java编写一个person类,包括姓名、性别、年龄、子女等属性,并封装了获得姓名、获得年龄、增加一岁、获得子女、设置子女等方法。子女属性为一个Person数组。
时间: 2023-09-17 08:05:49 浏览: 132
java代码-使用java构造Person类。包括姓名(name),性别和年龄(age)的源代码
5星 · 资源好评率100%
### 回答1:
```
public class Person {
private String name;
private String gender;
private int age;
private Person[] children;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void addYear() {
age++;
}
public Person[] getChildren() {
return children;
}
public void setChildren(Person[] children) {
this.children = children;
}
}
```
### 回答2:
Person类的示例代码如下所示:
```java
public class Person {
private String name;
private String gender;
private int age;
private Person[] children;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void increaseAge() {
age++;
}
public Person[] getChildren() {
return children;
}
public void setChildren(Person[] children) {
this.children = children;
}
public static void main(String[] args) {
Person child1 = new Person("Child1", "Male", 10);
Person child2 = new Person("Child2", "Female", 8);
Person[] children = {child1, child2};
Person parent = new Person("Parent", "Male", 35);
parent.setChildren(children);
System.out.println("Parent's name: " + parent.getName());
System.out.println("Parent's age: " + parent.getAge());
parent.increaseAge();
System.out.println("After increasing age, Parent's age: " + parent.getAge());
System.out.println("Parent's children: ");
for (Person child : parent.getChildren()) {
System.out.println("Child name: " + child.getName() + ", Child age: " + child.getAge());
}
}
}
```
这个Person类有姓名、性别、年龄、子女等属性,并且提供了获取姓名、获取年龄、增加一岁、获取子女、设置子女等方法。子女属性为一个Person数组。在示例代码中,我们创建了两个子女对象child1和child2,然后使用这两个子女对象初始化了一个子女数组children,然后创建了一个父母对象parent,并将子女数组设置为父母对象的子女属性。最后,我们使用该对象的一些方法进行测试并输出结果。
### 回答3:
```java
public class Person {
private String name;
private String gender;
private int age;
private Person[] children;
public Person(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void increaseAge() {
age++;
}
public Person[] getChildren() {
return children;
}
public void setChildren(Person[] children) {
this.children = children;
}
}
```
以上是一个用Java编写的`Person`类,包括姓名、性别、年龄、子女等属性,并封装了获得姓名、获得年龄、增加一岁、获得子女、设置子女等方法。子女属性为一个Person数组。在构造方法中,通过参数传入姓名、性别、年龄,并通过对应的get和set方法来获取和设置对应的属性值。增加一岁的方法`increaseAge()`会将年龄加1。子女属性`children`可以通过`getChildren()`方法获取,通过`setChildren()`方法设置。
阅读全文