overriding:一般都翻成覆載,不過我覺得翻成"改寫"會比較貼切
定義:
在繼承關係之下,子類別宣告與父類別相同的method名稱、相同的引數列、相同的method型態,子類別在呼叫method時候,會執行子類別的method。這就是所謂的overriding,子類別改寫父類別的方法
如果型態不同會compile error
如果引數列不同則是overloading多載
package inheritance;
class blueeyes {
public int attack = 3000;
int defense = 2500;
public void attack() {
System.out.println("attack is " + attack);
}
public void defense() {
System.out.println("defense is " + defense);
}
}
class whitestone extends blueeyes {
public int attack = 100;
public void attack(){
super.attack();
System.out.println("attck is is "+ attack);
}
public void effect() {
System.out.println("special summon blue eyes white dragon");
}
}
public class inheritance {
public static void main(String[] args) {
whitestone monster = new whitestone();
System.out.println(monster.attack);
monster.attack();//
blueeyes monster2 = new blueeyes();
System.out.println(monster2.attack);
}
}
沒有留言:
張貼留言