1.创建一个Person类,其定义如下:
属性 | 行为 |
---|---|
name:String | +study():void |
age:int | +showAge():void |
sex:int | +addAge(int i):int |
要求:(1)创建Person类的对象,设置该对象的name、age和sex属性,调用study方法,输出字符穿“studying”,调用showAge()方法显示age值,调用addAge()方法给对象的age属性值增加2岁。
(2)创建第二个对象,执行上述操作,体会同一个类的不同对象之间的关系。
代码:
1.创建类:
public class Person {
String name;
int age;
/**
* sex:1表明是男性
* sex:0表明是女性
*/
int sex;
public void study() {
System.out.println("studying");
public void showAge() {
System.out.println("age:" + age);
}
public int addAge(int i) {
age += i;
return age;
}
}
2.测试类
public class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
p1.name = "Wang";
p1.age = 18;
p1.sex = 1;
p1.study();
p1.showAge();
int newAge = p1.addAge(2);
System.out.println(p1.name + "的新年龄为:" + newAge);
// ***********************************
Person p2 = new Person();
p2.showAge();// 0
p2.addAge(10);
p2.showAge();// 10
}
}
输出:
studying
age:18
Wang的新年龄为:20
age:0
age:10