public class Person {
protected String name;
protected MyData birthday;
private static int count=0;
//四个构造函数
public Person(String name,MyData birthday)
{
this.name=name;
this.birthday=birthday;
count++;
}
//一下三个构造函数都是基于第一个来做的,所以只需要第一个count++
public Person(String name)
{
this(name,new MyData());
}
public Person()
{
this("未知",new MyData());
}
public Person(Person p)
{
this(p.name,new MyData(p.birthday));//深拷贝,系统根据new自动创建name,bitthday实例
}
//给外界提供修改name属性的接口
public void set(String name)
{
this.name=name;
}
//给外界提供修改birthday的接口
public void set(MyData birthday)
{
this.birthday=new MyData (birthday);
}
public String getName()
{
return this.name;
}
public MyData getBirthday()
{
return this.birthday;
}
public String toString()
{
return this.name+","+this.birthday.toString()+","+this.getAge()+"岁";
}
//public int getAge(int year)//year为对象在year年份的年龄
//{
// return year-this.birthday.getYear();
//}
public int getAge()
{
//return getAge(MyData.getThisYear());//MyData中默认的thisYear 是2009年
return MyData.getThisYear()-this.birthday.getYear();
}
//比较两个人的年龄
public int olderthan(Person p)
{
return this.getAge()-p.getAge();
}
public static void howmany()//统计Person对象的个数
{
System.out.println(count+"个Person对象");//访问静态对象Person.count
}
public void finalize()
{
System.out.println("释放对象("+this.toString()+")");
this.count--;
}
public static void main(String args[])
{
Person p1=new Person("李晓明",new MyData(1979,3,15));
person p2=new Person(p1);
p2.set(p2.getName().substring(0,2)+"东");
}
}
java类之Person
最新推荐文章于 2021-12-28 13:41:32 发布