回顧
四,深度認識類的繼承
1.子類對象的實例化過程
2.super關鍵字的使用
3.限制子類的訪問
學習小結
五、覆寫
“覆寫(Override)”的概念與“重載(Overload)”有相似之處。
1.方法的覆寫
當一個子類繼承一個父類,如果子類中的方法與父類中的方法的名稱、參數個數及類型且返回值類型等都完全一致時,就稱子類中的這個方法覆寫了父類中的方法。同理,屬性也可覆寫。
class Super{ //父類
返回值類型 方法名(參數列表){
}
}
class Sub extends Super{ // 子類
返回值 方法名(參數列表) // 與父類的方法同名,覆寫父類中的方法
}
package com.Javastudy2;
/**
* @author Y.W.
* @date 2017年9月5日 下午10:27:03
* @Description TODO 子類覆寫父類的實現
*/
public class P306_12_15 {
public static void main(String[] args) {
Student7 s = new Student7("Jack", 25, "HAUT");
// 此時調用的是子類中的talk()方法
System.out.println(s.talk());
}
}
class Person18 {
String name;
int age;
public String talk() {
return "I am:" + this.name + ",I am " + this.age + " years old";
}
}
class Student7 extends Person18 {
String school;
public Student7(String name, int age, String school) {
// 分別為屬性賦值
this.name = name; // super.name = name
this.age = age; // super.age = age
this.school = school;
}
// 此處覆寫Person中的talk()方法
public String talk() {
return "I am from " + this.school;
}
}
運行結果:
運行結果1
如何調用已經覆寫的父類的方法呢?
package com.Javastudy2;
/**
* @author Y.W.
* @date 2017年9月5日 下午10:27:03
* @Description TODO super調用父類的方法
*/
public class P307_12_16 {
public static void main(String[] args) {
Student8 s = new Student8("Jack", 25, "HAUT");
// 此時調用的是子類中的talk()方法
System.out.println(s.talk());
}
}
class Person19 {
String name;
int age;
public String talk() {
return "I am:" + this.name + ",I am " + this.age + " years old";
}
}
class Student8 extends Person19 {
String school;
public Student8(String name, int age, String school) {
// 分別為屬性賦值
this.name = name; // super.name = name
this.age = age; // super.age = age
this.school = school;
}
// 此處覆寫Person中的talk()方法
public String talk() {
// 調用父類的talk()
return super.talk() + "I am from " + this.school;
}
}
運行結果:
運行結果2
覆寫注意事項:
①.覆寫的方法的返回值類型必須和被覆寫的方法的返回值類型一致;
②.被覆寫的方法(子類)不能為static;
③.被覆寫的方法不能擁有比父類更為嚴格的訪問控制權限。
訪問權限大小:
私有(private)<默認(default)<公有(public)
2.屬性的覆寫
所謂的屬性覆蓋指的是子類定義了和父類之中名稱相同的屬性。
package com.Javastudy2;
/**
* @author Y.W.
* @date 2017年9月5日 下午10:59:08
* @Description TODO 屬性(數據成員)的覆寫
*/
public class P309_12_17 {
public static void main(String[] args) {
ComputerBook cb = new ComputerBook(); // 實例化子類對象
cb.print();
}
}
class Book2 {
String info = "Hello World.";
}
class ComputerBook extends Book2 {
int info = 100; // 屬性名稱與父類相同
public void print() {
System.out.println(info);
System.out.println(super.info);
}
}
運行結果:
運行結果3
思考
每天進步一點點,真的可以達到預期效果嗎,現在雖然還達不到每天,但我還是堅持著,有時間還是得堅持下去。還需要兩天,這章也可以搞定啦。
記于2017年9月5日夜