在上 Bill 的課之前我腦子的認知的多型其實只有廣義的兩種多型,沒想到竟然有四種。
父類別 Animal 子類別 Cat Bird
public abstract class Animal {
private int age = 0;
private String name = "Animal";
protected abstract void skill();
public int getAge() {
return age;
}
public void setAge(int age) {
if (age > 0) this.age = age;
else this.age = 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Cat extends Animal{
@Override
protected void skill() {
System.out.println("裝可愛");
}
}
public class Bird extends Animal{
@Override
protected void skill() {
System.out.println("飛");
}
}
主程式
public static void main(String[] args) {
Animal cat = new Cat();
Animal bird = new Bird();
cat.setAge(5);
cat.setName("Cat");
cat.skill();
bird.setAge(10);
bird.setName("bird");
bird.skill();
}
定義 Behavior 介面 eat & sleep 兩個方法,人會吃跟睡比較有規律,豬也會吃跟睡比較沒有規律。如果人沒有規律那就等同於豬?
介面 Behavior 類別 People Pig
public interface Behavior {
void eat();
void sleep();
}
public class People implements Behavior{
@Override
public void eat() {
System.out.println("吃三餐");
}
@Override
public void sleep() {
System.out.println("睡八小時");
}
}
public class Pig implements Behavior{
@Override
public void eat() {
System.out.println("睡飽吃");
}
@Override
public void sleep() {
System.out.println("吃飽睡");
}
}
主程式
public static void main(String[] args) {
Behavior people = new People();
Behavior pig = new Pig();
people.eat();
people.sleep();
pig.eat();
people.sleep();
}
泛型屬於參數式多型,也是在寫程式上很常用的一種多型。
// List<T> 角號中的 T 就是參數型別,依據參數的型別決定實作的內容
List<String> msgs = ArrayList<>();
C#可以多載運算子 ex: 可以重寫 == 的行為
Java 沒有重載運算子能功能
int age = 10;
double money = 100.5;
money += age;