W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
抽象是指在OOP中使類抽象的能力。抽象類是無法化的類。該類的所有其他函數(shù)仍然存在,并且以相同的方式訪問其字段,方法和構(gòu)造函數(shù)。您只是無法創(chuàng)建抽象類的。
如果一個類是抽象的并且無法化,則除非是子類,否則該類沒有太多用處。這通常是抽象類在設(shè)計階段出現(xiàn)的方式。父類包含子類集合的通用函數(shù),但是父類本身太抽象,無法單獨使用。
使用 abstract 關(guān)鍵字聲明一個類摘要。關(guān)鍵字出現(xiàn)在類聲明中類關(guān)鍵字之前的某個位置。下面顯示了如何繼承和使用抽象類的示例。
import std.stdio;
import std.string;
import std.datetime;
abstract class Person {
int birthYear, birthDay, birthMonth;
string name;
int getAge() {
SysTime sysTime=Clock.currTime();
return sysTime.year - birthYear;
}
}
class Employee : Person {
int empID;
}
void main() {
Employee emp=new Employee();
emp.empID=101;
emp.birthYear=1980;
emp.birthDay=10;
emp.birthMonth=10;
emp.name="Emp1";
writeln(emp.name);
writeln(emp.getAge);
}
當(dāng)我們編譯并運行上述程序時,我們將獲得以下輸出。
Emp1
37
與函數(shù)相似,類也可以是抽象的。此類函數(shù)的實現(xiàn)未在其類中給出,而應(yīng)在通過抽象函數(shù)繼承該類的類中提供。
import std.stdio;
import std.string;
import std.datetime;
abstract class Person {
int birthYear, birthDay, birthMonth;
string name;
int getAge() {
SysTime sysTime=Clock.currTime();
return sysTime.year - birthYear;
}
abstract void print();
}
class Employee : Person {
int empID;
override void print() {
writeln("The employee details are as follows:");
writeln("Emp ID: ", this.empID);
writeln("Emp Name: ", this.name);
writeln("Age: ",this.getAge);
}
}
void main() {
Employee emp=new Employee();
emp.empID=101;
emp.birthYear=1980;
emp.birthDay=10;
emp.birthMonth=10;
emp.name="Emp1";
emp.print();
}
當(dāng)我們編譯并運行上述程序時,我們將獲得以下輸出。
The employee details are as follows:
Emp ID: 101
Emp Name: Emp1
Age: 37
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: