inheritance public class Saving Account extends Bank Account
inheritance
public class Saving. Account extends Bank. Account{ private double interest. Rate; … public void add. Interest(){ double interest = get. Balance() * interest. Rate/100; deposit(interest); } ถงจะเปนสบคลาส กตองใชเมธอดเพอใหอาน private variable ได
public class Checking. Account extends Bank. Account{ นคอการ override public void deposit(double amount){ counter++ ; // นคอตรงทมเพมมาจากของเดม deposit(amount); //พยายามเรยกเมธอดของ superclass } แตนจะกลายเปนเรยกตวเอง infinite ตองใช super. deposit(amount) แทน
มนกมทตองใช ของตวทเรยกเมธอดไดนอยกวา type เชน Public void transfer(double amount, Bank. Account other){ withdraw(amount); อนนใชใน transfer other. deposit(amount); ได ไง เพราะ transfer มนควรจะใชกบบญชธ } นาคารแบบไหนกได. . Checking. Account my. Acc = new Checking. Account(. . ); mom. Account. transfer(1000, my. Acc);
ถาตองการเปลยน type อกขาง If (an. Object instanceof Bank. Account){ Bank. Account an. Account = (Bank. Account) an. Object; }
- Slides: 10