声明一个国家基类Country,包含国名、首都、人口等属性,派生出省类Province,增加省会城市、人口数量属性。定义派生类对象,并对相应信息进行输出
时间: 2024-11-27 15:21:14 浏览: 19
好的,首先我们声明一个基础的`Country`类,它包含通用的国家属性:
```java
public class Country {
private String name;
private String capital;
private int population;
// 构造函数
public Country(String name, String capital, int population) {
this.name = name;
this.capital = capital;
this.population = population;
}
// 获取和设置方法
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getCapital() { return capital; }
public void setCapital(String capital) { this.capital = capital; }
public int getPopulation() { return population; }
public void setPopulation(int population) { this.population = population; }
// 打印基本信息
@Override
public String toString() {
return "Country{" +
"name='" + name + '\'' +
", capital='" + capital + '\'' +
", population=" + population +
'}';
}
}
```
接着,我们创建一个派生类`Province`,它从`Country`类继承并添加特有的属性:
```java
public class Province extends Country {
private String provincialCapital;
private int provincePopulation;
// 构造函数
public Province(String name, String capital, int population, String provincialCapital, int provincePopulation) {
super(name, capital, population); // 调用父类构造函数
this.provincialCapital = provincialCapital;
this.provincePopulation = provincePopulation;
}
// 获取和设置省会城市和人口数量
public String getProvincialCapital() { return provincialCapital; }
public void setProvincialCapital(String provincialCapital) { this.provincialCapital = provincialCapital; }
public int getProvincePopulation() { return provincePopulation; }
public void setProvincePopulation(int provincePopulation) { this.provincePopulation = provincePopulation; }
// 打印更多信息
@Override
public String toString() {
return "Province{" +
"super.toString() +\n" + // 调用父类toString方法显示基本信息
"provincialCapital='" + provincialCapital + '\'' +
", provincePopulation=" + provincePopulation +
'}';
}
}
```
现在我们可以创建`Country`和`Province`类型的实例并打印它们的信息:
```java
// 创建一个Country实例
Country country = new Country("中国", "北京", 1400000000);
System.out.println(country);
// 创建一个Province实例
Province province = new Province("广东省", "广州", 113400000, "广州市", 113400000);
System.out.println(province);
```
阅读全文