繼承與多型的乙個簡單例項

2021-08-30 02:28:23 字數 3273 閱讀 7296

程式結構:

父為person類,person類個子類student和employee,employee類又有兩個子類,staff和faculty。

繼承即子類可以繼承父類的資料域和方法:

student類和employee類繼承了person類的資料域name,address phonenumber e_mail classname 以及他們的set方法和get方法。同時emloyee類中宣告了新的資料域office,wage,date以及他們的set get方法。student類有新的grade資料域和方法。

staff和faculty類繼承了employee類中的所有方法,包括從person類中繼承來的方法,同時有定義了自己的新方法。

同時,子類通過super呼叫了父類設定日期的構造方法和tostring方法。

多型:testperson類中建立了student,staff和faculty型別的物件

在呼叫tostring時,每個類都有自己對tostring方法的實現(子類覆蓋了父類的tostring方法),最終的輸出結果取決於物件的型別,體現了動態繫結。

//父類

public

class

person

public string gete_mail()

public

void

setphonenumber()

public string getphonenumber()

public

void

setclassname()

public string getclassname()

public

void

setaddress()

public string getaddress()

public

void

setname()

public string getname()

public string tostring()

}

package person;

public

class

student

extends

person

public string getgrade()

public

student

(string classname,string name,string grade,string phonenumber,string e_mail,string address)

public string tostring()

}

package person;

public

class

employee

extends

person

public

void

setoffice()

public string getoffice()

public

void

setwage()

public

double

getwage()

public string tostring()

}

package person;

//教員

public

class

faculty

extends

employee

public string getrank()

public

void

settime()

public string gettime()

public

faculty

(string classname,string name,string rank,string phonenumber,string e_mail,string address,string office,

double wage,string time,

int year,

int month,

int day)

public string tostring()

}

package person;

//職員

public

class

staff

extends

employee

public string getstafftitle()

public

staff

(string classname,string name,string stafftitle,string phonenumber,string e_mail,string address,string office,

double wage,

int year,

int month,

int day)

public

staff()

public string tostring()

}

package person;

public

class

mydate

public

void

setyear()

public

static

intgetyear()

public

void

setmonth()

public

static

intgetmonth()

public

void

setday()

public

static

intgetday()

}

package person;

public

class

testperson

public

static

void

m(object x)

}

執行結果

Lua 繼承與多型(例項)

交通工具類 vehicle 速度 通過里程數求時間 父類local vehicle 1.1父類構造function vehicle new speed local o o.speed speed or 0 setmetatable o,self self.index self return o en...

關於多型的乙個經典例項

廢話不多說,直接上 public class a public string show a obj public class b extends a public string show a obj public class c extends b public class d extends b ...

乙個簡單的爬蟲例項

獲取網頁html文字內容 usr bin python coding utf 8 import urllib import re 根據url獲取網頁html內容 defgethtmlcontent url page urllib.urlopen url return page.read 從html中...