一、爲什麼要繼承:代碼更簡潔、靈活
父類:
public class Student {
//屬性
private String name;
public void setName(String n){
name = n;
}
//學生的行爲方法
public void study(){
System.out.println(name+”學習”);
}
}
子類:
public class UNStudent {
}
二、繼承了什麼:屬性和方法
子類的對象可以使用父類的方法
父類的對象不可使用子類的方法
public static void main(String[] args) {
UNStudent s = new UNStudent();
uns.setName(“iris”);
Uns.study();
}
三、自動轉型和強制轉型
自動(向上):Student s1 = new UNStudent();
強制:UNStudent s2 = (UNStudent)s2;
實例:
//自動轉型在當父類被作爲其他方法的參數時較爲有效
class teacher(){
…
public void teach(Student s){
System.out.println(s.name+”正在被教”);
}
}
//可以使用子類作爲參數,自動向上轉型。
//uns爲UNStudent類的對象,可以向上轉型爲Student,作爲參數輸入
t.teach(uns);
四、方法的重寫
子類重寫父類中的方法:
public class UNStudent {
//大學生的行爲方法
public void study(){
System.out.println(name+”進行大學學習。”);
}
}
五、接口
1、接口的定義
public interface 接口名{
//屬性爲常量
public static final int 屬性名(大寫)=0;
int 屬性名(大寫)=0;
//方法
public abstract void 屬性方法名();
void 屬性方法名();
}
//例子:五子棋Config接口,用於存儲靜態常量,該常量在其他類中都能用到,不用多次定義和賦值。
public interface Config {
public static final int X0=30;
public static final int Y0=30;
public static final int SIZE=40;
public static final int LINE=19;
//保存棋子,二維數組
public int chessArray[][] = new int[LINE][LINE];
}
final:
放在類前,表示該類——不允許繼承
放在方法前,表示該方法——不允許重寫
放在常量前,表示該常量——不允許修改
2、接口的實現
(a)格式
public class 子類 extends 父類 implements 接口1,接口2….{
}
(b)方法
接口類要重寫所有抽象方法
public class 子類 implements 接口1{
//實現接口的方法,1需要寫public,2去掉abstract
public void 方法(){
//方法體
}
}
//例子:重繪函數
//放大縮小時,窗體自動調用重繪函數,我們重新繪製存在shapeArray中的線條
public void paint(Graphics g) {
//調用重繪
super.paint(g);
int i;
for(i=0;i<shapeArray.length;i++){
if(shapeArray[i]!=null){
shapeArray[i].Redraw(g);
}
else
break;
}
System.out.println("重繪");
}
(c)主函數中使用
//創建對象,Person爲接口,Student爲子類
Person p1 = new Student;
//調用重寫父類中的方法
p1.study();
ps、特例
-
構造函數:super( );
無參函數會在子類中自動調用,有參函數需要在子類調用。
class 類名(參數類型 參數名,…){
super(參數名);
}
//例子:
public UNStudent(String name){
super(name);
}
建議在父類中寫一個無參構造函數,則不會報錯。