Yenza iklasi eThintayo kwiJava

NguDoug Lowe

An iklasi engaqondakaliyo kwiJava yiklasi equlethe enye okanye ngaphezulu iindlela ezingabonakaliyo , Yindlela elula yokubhengeza ngaphandle komzimba- Oko kukuthi, ngaphandle kwekhowudi efanelekileyo yokuphumeza iklasi okanye indlela. Indlela ebambekayo ifana neprototype yendlela ethile, ebhengeza uhlobo lwendlela ebuyayo kunye noluhlu lweparameter kodwa inganikezeli ngokwenyani yendlela.



Awunakho ukuqinisa iklasi engaqondakaliyo. Nangona kunjalo, unokwenza i-subclass eyandisa iklasi engaqondakaliyo kwaye ibonelele ngokumiliselwa kweendlela ezingaqondakaliyo ezichazwe kudidi olungaqondakaliyo. Ungayiqinisekisa i-subclass.



Ukwenza indlela engaqondakaliyo, uchaza isitshintshiabstractkwaye ubeke endaweni yomzimba wendlela nge semicolon:

public abstract return-type method-name(parameter-list);

Nanku umzekelo:



 public abstract int hit(int batSpeed);

Ukwenza iklasi engaqondakaliyo, usebenzisa i-abstractkwisibhengezo seklasi kwaye ubandakanye ubuncinci indlela enye ebambekayo. Umzekelo:

public abstract class Ball { public abstract int hit(int batSpeed); }

Unokwenza i-subclass evela kwiklasi engaqondakaliyo ngolu hlobo:

public class BaseBall extends Ball { public int hit(int batSpeed) { // code that implements the hit method goes here } }

Xa ugoba iklasi engabanjwanga, i-subclass kufuneka ibonelele ngokuphunyezwa kwendlela nganye engafakwanga kwiklasi ye-abstract. Ngamanye amagama, kufuneka ibambe ngaphezulu kwendlela nganye engafakwanga.



Iiklasi ze-Abstract ziluncedo xa ufuna ukwenza uhlobo oluqhelekileyo olusetyenziswa njenge-superclass ezimbini okanye ezingaphantsi, kodwa i-superclass ngokwayo ayibonisi eyona nto. Ukuba bonke abasebenzi bahlawulwa umvuzo okanye ngeyure, umzekelo, kuyavakala ukwenza into engabonakaliyoUmqeshwaclass kwaye uyisebenzise njengodidi olusisiseko lwefayile ye-Umsebenzi ohlawulelwayokwayeNgeyureEmsebenziniiziqwengana.

Nazi iinkcukacha ezimbalwa ezongezelelweyo ngokubhekisele kwiiklasi ezingaqondakaliyo:

  • Ayizizo zonke iindlela zodidi olungaqondakaliyo ekufuneka zingafakwanga. Iklasi inokunika ukumiliselwa kwezinye zeendlela zayo kodwa hayi ezinye. Ngapha koko, nokuba udidi alunazo iindlela ezingaqondakaliyo, usengabhengeza ukuba alunabungqina. (Kwimeko enjalo, nangona kunjalo, iklasi ayinakuqinisekiswa.)

  • Indlela yabucala ayinakubonwa. Zonke iindlela ezingaqondakaliyo kufuneka zibe sesidlangalaleni.

  • Iklasi ayinakuba bobabiniabstractkwayeokokugqibela.