(1)定义Person类,包含3个成员变量name(姓名)、age(年龄)、sex(性别)和3个构造方法,其中无参构造方法初始化变量;一个有参构造方法的参数为与成员变量小脑瓜痛的参数列表,通过传递的参数初始化变量;另一个有参构造方法的参数为类的对象,通过对象初始化变量,然后定义showInfo()方法显示信息 (2)另外,定义City类继承Person类,包括成员变量name(城市名)和3个构造方法,使用super关键字调用父类的构造方法和成员变量对父类的成员变量进行初始化,然后对子类新增的成员变量进行初始化,最后重写showInfo()方法。
时间: 2024-01-22 10:02:14 浏览: 75
好的,下面是代码实现:
```
public class Person {
String name;
int age;
String sex;
public Person() {
name = "Unknown";
age = 0;
sex = "Unknown";
}
public Person(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
public Person(Person person) {
this.name = person.name;
this.age = person.age;
this.sex = person.sex;
}
public void showInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Sex: " + sex);
}
}
public class City extends Person {
String cityName;
public City() {
super();
cityName = "Unknown";
}
public City(String name, int age, String sex, String cityName) {
super(name, age, sex);
this.cityName = cityName;
}
public City(Person person, String cityName) {
super(person);
this.cityName = cityName;
}
@Override
public void showInfo() {
super.showInfo();
System.out.println("City name: " + cityName);
}
}
```
以上代码中,首先定义了Person类,包含了3个成员变量和3个构造方法,其中一个无参构造方法、一个有参构造方法和一个参数为Person类对象的有参构造方法。Person类还定义了showInfo()方法,用于显示信息。
接着定义了City类,继承自Person类。City类新增了一个成员变量cityName,并且定义了三个构造方法,分别调用了父类的构造方法进行变量的初始化。City类还重写了父类的showInfo()方法,显示了城市名称。
在主函数中,可以进行如下测试:
```
public static void main(String[] args) {
Person person1 = new Person();
person1.showInfo();
System.out.println("--------------------");
Person person2 = new Person("Tom", 20, "Male");
person2.showInfo();
System.out.println("--------------------");
Person person3 = new Person(person2);
person3.showInfo();
System.out.println("--------------------");
City city1 = new City();
city1.showInfo();
System.out.println("--------------------");
City city2 = new City("Lucy", 22, "Female", "New York");
city2.showInfo();
System.out.println("--------------------");
City city3 = new City(person2, "London");
city3.showInfo();
}
```
输出结果如下:
```
Name: Unknown
Age: 0
Sex: Unknown
--------------------
Name: Tom
Age: 20
Sex: Male
--------------------
Name: Tom
Age: 20
Sex: Male
--------------------
Name: Unknown
Age: 0
Sex: Unknown
City name: Unknown
--------------------
Name: Lucy
Age: 22
Sex: Female
City name: New York
--------------------
Name: Tom
Age: 20
Sex: Male
City name: London
```
阅读全文