Presentation is loading. Please wait.

Presentation is loading. Please wait.

JAVA 程式設計與資料結構 第七章 繼承與Interface.

Similar presentations


Presentation on theme: "JAVA 程式設計與資料結構 第七章 繼承與Interface."— Presentation transcript:

1 JAVA 程式設計與資料結構 第七章 繼承與Interface

2 繼承 一個class可以承繼另一個class,被繼承的class稱為super class,繼承的class 稱為subclass。用關鍵字extends來修飾。 繼承的物件擁有被繼承物件的所有變數以及方法,除非繼承的物件設計新的方法覆蓋過被繼承物件中的方法。

3 繼承自class Employee,使用關鍵字extends super代表被繼承的物件,也就是Employee
繼承範例 class OfficeEmployee extends Employee { double weight; double height; OfficeEmployee (String s, int i) { super(s, i); } // Constructor 繼承自class Employee,使用關鍵字extends super代表被繼承的物件,也就是Employee

4 Overriding 如果在子類別裡宣告跟父類別相同的方法(擁有相同的變數),那麼在子類別裡的方法將會覆蓋過父類別的方法,稱為overriding。 也就是說如果繼承的class內擁有與被繼承的class中同名的method,則以繼承的class中所定義的為準。

5 Abstract 有時候當我們設計一個class,它並沒有被instantiated的必要,也就是說我們不會new一個這樣的物件,這個時候我們可以將其設計為abstract。 被定義為abstract的class不能被instantiated,也就是說無法使用new關鍵字來建立一個instance,但是此class可以被繼承。 被abstract修飾的方法無須有內容,必須在繼承的class中定義。

6 Abstract修飾的方法,在繼承的class中定義其用法。
範例 abstract class Student{ String name; String ID; int grade; public Student() { } // Constructor    abstract public void computeGrade(int extra); public String getID() { return ID; }//getID() }// Student Abstract修飾的方法,在繼承的class中定義其用法。

7 Interface及多重繼承 在Interface中可以宣告abstract的方法(method)及常數(constant),而讓其它的class來安裝這些方法。 但是Interface僅提供方法的宣告部分,並不提供實現(implements)的部分,因此Interface純為設計的用途,不像class除了提供方法(method)的宣告之外,也可以實現(inplements),因此同時具有設計及實現的功能。 Interface間也可以相互繼承。

8 此class實現AreaInterface,必須完成其中所定義的方法,因為楮瑥牦慣e中定義的方法視為abstract修飾的方法。
Implements 此interface中定義兩個方法,其純粹只是一個想法。 public interface AreaInterface{ double area(); // 面積 double circ(); // 週長 }//AreaInterface 此class實現AreaInterface,必須完成其中所定義的方法,因為楮瑥牦慣e中定義的方法視為abstract修飾的方法。 class SquareAreaImplements implements AreaInterface{ double w, h; SquareAreaImplements (double w, double h) { this.w = w; this.h = h; }//Constructor public double area() {return w*h;} public double circ() {return 2*(w+h);} }// SquareAreaImplements

9 Class C extends classA implements interfaceB
多重繼承 Class A Interface B extends implements Class C extends classA implements interfaceB


Download ppt "JAVA 程式設計與資料結構 第七章 繼承與Interface."

Similar presentations


Ads by Google