成員變量的隱藏和方法的重寫
Goods.java
public class Goods { public double weight; public void oldSetWeight(double w) { weight=w; System.out.println("double型的weight="+weight); } public double oldGetPrice() { double price = weight*10; return price; } }
CheapGoods.java
public class CheapGoods extends Goods { public int weight; public void newSetWeight(int w) { weight=w; System.out.println("int型的weight="+weight); } public double newGetPrice() { double price = weight*10; return price; } }
Example5_3.java
public class Example5_3 { public static void main(String args[]) { CheapGoods cheapGoods=new CheapGoods(); //cheapGoods.weight=198.98; 是非法的,因為子類對象的weight已經是int型 cheapGoods.newSetWeight(198); System.out.println("對象cheapGoods的weight的值是:"+cheapGoods.weight); System.out.println("cheapGoods用子類新增的優惠方法計算價格:"+ cheapGoods.newGetPrice()); cheapGoods.oldSetWeight(198.987); //子類對象調用繼承的方法操作隱藏的double型變量weight System.out.println("cheapGoods使用繼承的方法(無優惠)計算價格:"+ cheapGoods.oldGetPrice()); } }
子類對繼承父類方法的重寫
University.java
public class University { void enterRule(double math,double english,double chinese) { double total=math+english+chinese; if(total>=180) System.out.println("考分"+total+"達到大學最低錄取線"); else System.out.println("考分"+total+"未達到大學最低錄取線"); } }
ImportantUniversity.java
public class ImportantUniversity extends University{ void enterRule(double math,double english,double chinese) { double total=math+english+chinese; if(total>=220) System.out.println("考分"+total+"達到重點大學錄取線"); else System.out.println("考分"+total+"未達到重點大學錄取線"); } }
Example5_4.java
public class Example5_4 { public static void main(String args[]) { double math=64,english=76.5,chinese=66; ImportantUniversity univer = new ImportantUniversity(); univer.enterRule(math,english,chinese); //調用重寫的方法 math=89; english=80; chinese=86; univer = new ImportantUniversity(); univer.enterRule(math,english,chinese); //調用重寫的方法 } }