练习题:两个对象的邂逅
- 定义一个类代表“人”,含有姓名和年龄,而且具有打招呼的功能,根据类创建两个对象并且赋值,让两个对象分别和对方打招呼
// 先创建一个类
public class person
{
private String name; //姓名
private int age; //年龄
public Person() //无参
{
}
public person(String name, int age) //有参数
{
this.name = name;
this.age = age;
}
public void sayHello(String who)
{
System.out.println(who + "你好,我是" + this.name + ",今年" + this.age + "岁。");
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
//创建对象
public class Demoperson
{
public static void main(String[] args)
{
Person one = new Person(); //默认构造
one.setName("一一");
one.setAge(20);
Person two = new Person("二二",18); //有参构造
//先让一一和二二打招呼
//效果应该是:二二你好,我是一一,今年20岁。
one.sayHello(two.getName());
//然后让二二给一一打招呼
//效果应该是:一一你好,我是二二,今年18岁.
two.sayHello(one.getName());
}
}