编写Java程序,创建一个 Person 类,该类中有一个类成员变量 country、一个实例变量 name 和另一个实例变量 age。

返回本章节

返回作业目录


需求说明:

  • 创建一个 Person 类,该类中有一个类成员变量 country、一个实例变量 name 和另一个实例变量 age。
  • country 表示地区,name 表示姓名,age 表示年龄。
  • 创建 3 个 Person 对象,并分别给这3个对象的属性赋值。
  • 分别获取3个Person对象的属性。

实现思路:

定义Person类的实现思路如下:

  1. 创建人类(Person)。
  2. 定义 int 实例变量 age,String 实例变量 name,String 类变量 country。
  3. 创建 3 个 Person对象,给 3 个 Person 对象的姓名和年龄赋值,再通过类名给成员变量 country 赋值。
  4. 创建一个测试类 PersonTest,输出3个Person对象的属性信息。

实现代码:

Person 类


public class Person {
	static String country;
	String name;
	int age;
}

test 类

public class test1 {

	public static void main(String[] args) {
		Person.country = "云南";
		Person p1 = new Person();
		p1.name = "小杨";
		p1.age = 18;
		Person p2 = new Person();
		p2.name = "小明";
		p2.age = 19;
		Person p3 = new Person();
		p3.name = "小金";
		p3.age = 20;
		System.out.println("地区:"+Person.country+"\t姓名:"+p1.name+"\t年龄:"+p1.age);
		System.out.println("地区:"+Person.country+"\t姓名:"+p2.name+"\t年龄:"+p2.age);
		System.out.println("地区:"+Person.country+"\t姓名:"+p3.name+"\t年龄:"+p3.age);
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_44893902/article/details/106017265