重学JAVA基础(五):面向对象
1.封装
import java.util.Date; public class Human { protected String name; protected BirthDay birthDay; protected String sex; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public BirthDay getBirthDay() { return birthDay; } public void setBirthDay(BirthDay birthDay) { this.birthDay = birthDay; } public int getAge(){//封装方法 if(birthDay!=null){ Date nowDate = new Date(System.currentTimeMillis()); int year = nowDate.getYear()+1900; int month = nowDate.getMonth()+1; int day = nowDate.getDate(); int age = year - this.birthDay.getYear(); if(this.birthDay.getMonth()>month){ return age-1; }else if(this.birthDay.getMonth()==month){ if(this.birthDay.getDay()>=day){ return age-1; } } return age; } return 0; } public String toString(){ return "name:"+name+" sex:"+sex+" age:"+getAge(); } public String toString(Human human){ return this+""; } public Human(){ } public Human(String name,String sex) { super(); this.name = name; this.sex = sex; } public Human(String sex) { super(); this.sex = sex; } public Human(String name,String sex,int year,int month,int day) { super(); this.name = name; this.birthDay = new BirthDay(year, month, day); this.sex = sex; } }
public class BirthDay { private int year; private int month; private int day; public int getYear() { return year; } public void setYear(int year) { this.year = year; } public int getMonth() { return month; } public void setMonth(int month) { this.month = month; } public int getDay() { return day; } public void setDay(int day) { this.day = day; } public BirthDay(){ } public BirthDay(int year, int month, int day) { super(); this.year = year; this.month = month; this.day = day; } }
2.继承
public class Woman extends Human{ public Woman(){ super("Woman"); } public Woman(String name){ super(name,"Woman"); } public String toString(){ return " I am Woman,"+super.toString(); } public String toString(Woman woman){ return woman+""; } }
public class Man extends Human{ public Man(){ super("Man"); } public Man(String name){ super(name,"Man"); } public String toString(){ return " I am Man,"+super.toString(); } public String toString(Man man){ return man+""; } }
3.多态
public class TestOO { public static void main(String[] args) { Human man = new Man("man"); Human woman = new Woman("woman"); System.out.println(woman.toString(man)); System.out.println(man.toString(woman)); } }
运行结果:
I am Woman,name:woman sex:Woman age:0 I am Man,name:man sex:Man age:0