摘要:物件概念:多型、抽象類別、介面
物件概念
https://github.com/JustinSDK/JavaSE6Tutorial/blob/master/docs/CH08.md#82-%E5%A4%9A%E5%9E%8Bpolymorphism
多型(Polymorphism)
====================================二個類別各做各的method======
public void execute(Class1 c1) {
c1.doSomething();
}
public void execute(Class2 c2) {
c2.doSomething();
}
******************Class1 與 Class2 都繼承 ParentClass ***********
public void execute(ParentClass c) {
c.doSomething();
}
抽象類別(Abstract class)
=============================================================
public class ConcreteCircle {
private double radius;
public void setRedius(int radius) { this.radius = radius; }
public double getRadius() { return radius; }
public void render() {
System.out.printf("畫一個半徑 %f 的實心圓\n", getRadius());
}
}
public class HollowCircle {
private double radius;
public void setRedius(int radius) { this.radius = radius; }
public double getRadius() { return radius; }
public void render() {
System.out.printf("畫一個半徑 %f 的空心圓\n", getRadius());
}
}
**************************抽出共用的方法為抽象類別********************
//part1:
public abstract class AbstractCircle {
protected double radius;
public void setRedius(int radius) { this.radius = radius; }
public double getRadius() { return radius; }
public abstract void render();
}
//part2:類別用繼承方式來使用共用方法
public class HollowCircle extends AbstractCircle {
public HollowCircle() {}
public HollowCircle(double radius) {
this.radius = radius;
}
public void render() {
System.out.printf("畫一個半徑 %f 的空心圓\n", getRadius());
}
}
介面(Interface):類別A、B實作一個介面,類別C使用介面的Method時,會同時執行類別A、B
=====================================================================
//介面
public interface IRequest {
public void execute();
}
//類別A
public class HelloRequest implements IRequest {
private String name;
public HelloRequest(String name) {
this.name = name;
}
public void execute() {
System.out.printf("哈囉 %s!%n", name);
}
}
//類別B
public class WelcomeRequest implements IRequest {
private String place;
public WelcomeRequest(String place) {
this.place = place;
}
public void execute() {
System.out.printf("歡迎來到 %s!%n", place);
}
}
//類別C
public class RequestDemo {
public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
int n = (int) (Math.random() * 10) % 2; // 隨機產生
switch (n) {
case 0:
doRequest(new HelloRequest("良葛格"));
break;
case 1:
doRequest(new WelcomeRequest("Wiki 網站"));
}
}
}
public static void doRequest(IRequest request) {
request.execute();
}
}
執行結果如下:
哈囉 良葛格!
哈囉 良葛格!
哈囉 良葛格!
歡迎來到 Wiki 網站!
哈囉 良葛格!
哈囉 良葛格!
歡迎來到 Wiki 網站!
哈囉 良葛格!
歡迎來到 Wiki 網站!
歡迎來到 Wiki 網站!