多型入門

Java 物件導向程式設計入門

Sani Yusuf

Lead Software Engineering Content Developer

示範多型

  • 多型是物件導向程式設計(OOP)中的概念,讓物件能以多種型態存在
  • 展示類別繼承

  // Abstract Car class
  abstract class Car {

    // Abstract drive method
    abstract void drive(); 
    // No Code Implementation 

  }

  // Toyota class inherits Car class
  class Toyota extends Car {  

  }
  // Tesla class inherits Car class
  class Tesla extends Car {  

  }
  // Lamborghini class inherits Car class
  class Lamborghini extends Car {          

  }
Java 物件導向程式設計入門

覆寫方法

  • 使用 @Override 關鍵字可自訂方法實作
  // Abstract Car class
  abstract class Car {

    // Abstract drive method
    abstract void drive(); 
    // No Code Implementation 

  }


 class Toyota extends Car {  
   @Override // Keyword used to override
    void drive() {
      // Toyota specific implementation code
    }  
 }
 class Tesla extends Car {   
   @Override
    void drive() {
      // Tesla specific implementation code
    } 
 }
 class Lamborghini extends Car {  
   @Override
    void drive() {
      // Lamborghini specific implementation code
    }   
 }
Java 物件導向程式設計入門

覆寫介面方法


  // ElectricCar interface
  interface ElectricCar {

    abstract void charge(); 
    // No Code Implementation 

  }


  • 使用介面方法時建議加上 @Override

  // Tesla class implementing 
  // ElectricCar interface
  class Tesla implements ElectricCar {

    // charge method must be implemented
    @Override
    void charge(){
      // Tesla specific charge implementation
      // Selective inheritance with interface
    }          
  }













Java 物件導向程式設計入門

方法多載

  • 多載允許同名方法有不同實作

  // Toyota class 
  class Toyota {   

    void drive() {
      // First implementation of drive method
    }

// Overloaded drive method void drive(int topSpeed) { // Second implementation of drive } }
Java 物件導向程式設計入門

建構子多載

  • 建構子也可多載,在同一類別中有多個版本
  // Honda class
  class Honda {
    // First Constructor
    public Honda(String color,
                 String model) {

    }

// Second Constructor public Honda(String color, String model, String licensePlate) { } }

  public class Main {  
    public static void main(
      String[] args) {

      // First Constructor usage
      Honda hondaOne = 
        new Honda("Red", "Accord");


// Second Constructor usage Honda hondaTwo = new Honda("Red", "Civic", "FST-1977"); } }
Java 物件導向程式設計入門

一起來練習吧!

Java 物件導向程式設計入門

Preparing Video For Download...