1. Encapsulation
Importjava.util.Date; Public classHuman {protectedString name; protectedBirthDay BirthDay; protectedString sex; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicString Getsex () {returnsex; } Public voidsetsex (String sex) { This. Sex =sex; } PublicBirthDay Getbirthday () {returnBirthDay; } Public voidSetbirthday (BirthDay BirthDay) { This. BirthDay =BirthDay; } Public intGetage () {//encapsulation methodif(birthday!=NULL) {Date nowdate=NewDate (System.currenttimemillis ()); intYear = Nowdate.getyear () +1900; intmonth = Nowdate.getmonth () +1; intDay =nowdate.getdate (); intAge = year- This. Birthday.getyear (); if( This. Birthday.getmonth () >month) { returnAge-1; }Else if( This. Birthday.getmonth () = =month) { if( This. Birthday.getday () >=Day ) { returnAge-1; } } returnAge ; } return0; } PublicString toString () {return"Name:" +name+ "Sex:" +sex+ "Age:" +Getage (); } PublicString toString (Human Human) {return This+""; } PublicHuman () {} PublicHuman (String name,string sex) {Super(); This. Name =name; This. Sex =sex; } PublicHuman (String sex) {Super(); This. Sex =sex; } PublicHuman (String name,string sex,intYearintMonthintDay ) { Super(); This. Name =name; This. BirthDay =NewBirthDay (year, month, day); This. Sex =sex; } }
Public classBirthDay {Private intYear ; Private intmonth; Private intDay ; Public intgetYear () {returnYear ; } Public voidSetyear (intYear ) { This. Year =Year ; } Public intGetMonth () {returnmonth; } Public voidSetmonth (intmonth) { This. Month =month; } Public intGetDay () {returnDay ; } Public voidSetday (intDay ) { This. Day =Day ; } PublicBirthDay () {} PublicBirthDay (intYearintMonthintDay ) { Super(); This. Year =Year ; This. Month =month; This. Day =Day ; } }
2. Inheritance
Public classWomanextendshuman{ PublicWoman () {Super("Woman"); } PublicWoman (String name) {Super(Name, "Woman"); } PublicString toString () {return"I am Woman," +Super. toString (); } PublicString toString (Woman Woman) {returnWoman+ ""; }}
Public classMansextendshuman{ PublicMan () {Super("Man"); } PublicMan (String name) {Super(Name, "Man"); } PublicString toString () {return"I am Man," +Super. toString (); } PublicString toString (Mans man) {returnMan+ ""; } }
3. polymorphic
Public class Testoo { publicstaticvoid main (string[] args) { new Man (the "Man") ; New Woman ("Woman"); System.out.println (Woman.tostring (man)); System.out.println (man.tostring (woman));} }
Operation Result:
I am Woman,name:woman Sex:woman age:0 I am Man,name:man Sex:man age:0
Re-learning Java Basics (V): Object-oriented