資源描述:
《上轉(zhuǎn)型對象多態(tài)示例java源程序》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、Person.java源程序清單publicclassPerson{privateStringname;privateintage;publicPerson(){name="";age=0;}publicPerson(Stringname,intage){this.name=name;if(age<0){age=0;}this.age=age;}publicvoidsetName(Stringname){this.name=name;}publicStringgetName(){returnname;}publicvoidsetAge(intage){if(a
2、ge<0){age=0;}this.age=age;}publicintgetAge(){returnage;}publicvoiddisplay(){System.out.println("姓名:"+name+"t年齡:"+age);}}Student.java源程序清單publicclassStudentextendsPerson{privateStringschoolName;Student(){schoolName="";}Student(Stringname,intage,StringschoolName){super(name,age);this
3、.schoolName=schoolName;}publicvoidsetSchoolName(StringschoolName){this.schoolName=schoolName;}publicStringgetSchoolName(){returnschoolName;}publicvoiddisplay(){super.display();System.out.println("學校名稱:"+schoolName);}}Worker.java源程序清單publicclassWorkerextendsPerson{privateLongyield;pu
4、blicWorker(){yield=newLong(0);}publicWorker(Stringname,intage,Longyield){super(name,age);this.yield=yield;}publicvoidsetYield(Longyield){this.yield=yield;}publicLonggetYield(){returnyield;}publicvoiddisplay(){super.display();System.out.println("產(chǎn)量:"+yield.longValue());}}Viewer.java源
5、程序清單publicclassViewer{publicvoidview(Personp){p.display();}}Test.java源程序清單publicclassTest//含有main()方法的主類{publicstaticvoidmain(String[]args){Students=newStudent("張三",24,"我的JAVA學堂");//定義Student類變量并實例化Workerw=newWorker("Jone",40,newLong(1005));//定義Worker類變量并實例化Viewerv=newViewer();v.vie
6、w(s);//調(diào)用Student對象的實例方法v.view(w);//調(diào)用Worker對象的實例方法}}