编写Person类,包含3个属性name(String)\age(int)\nationality(String), 1个方法void Speak(); 编写HelloChina类,包含1个属性Person
时间: 2024-03-09 11:48:28 浏览: 70
设计一个Personal类
,1个方法void sayHello(); 在sayHello()方法中调用Person类的Speak()方法,输出"Hello, China!"。
以下是Person类的代码:
```
public class Person {
private String name;
private int age;
private String nationality;
public Person(String name, int age, String nationality) {
this.name = name;
this.age = age;
this.nationality = nationality;
}
public void Speak() {
System.out.println("Hello, I am " + name + ". I am " + age + " years old. I am from " + nationality + ".");
}
}
```
以下是HelloChina类的代码:
```
public class HelloChina {
private Person person;
public HelloChina(Person person) {
this.person = person;
}
public void sayHello() {
System.out.println("Hello, China!");
person.Speak();
}
}
```
在主函数中,可以这样使用:
```
Person person = new Person("Tom", 20, "USA");
HelloChina hello = new HelloChina(person);
hello.sayHello();
```
阅读全文