- Hands-On Design Patterns with Java
- Dr. Edward Lavieri
- 268字
- 2021-06-24 14:57:58
Polymorphism
Polymorphism is not a word that non-OOP programmers are likely familiar with. The term polymorphism is generally defined as appearing in multiple forms. In OOP, polymorphism states that different types of objects can be accessed via a common interface. This can be achieved by writing overloaded constructors and methods and is covered later in this chapter. Polymorphism can also be achieved by having subclasses override superclass methods.
Let's take a simple look at this using Java code:
- First, we create a Vehicle class that, by default, extends Java's Object class.
- Next, we create a TwoWheeled class that extends the Vehicle class.
- Then, we create a Bicycle class that extends the TwoWheeled class.
- Lastly, we create a Driver class that creates an instance of the Bicycle class and runs four checks using the instanceof keyword:
public class Vehicle {
}
public class TwoWheeled extends Vehicle {
}
public class Bicycle extends TwoWheeled {
}
public class Driver {
public static void main(String[] args) {
Bicycle myBike = new Bicycle();
System.out.println("\nmyBike \"Instance of\" Checks");
if (myBike instanceof Bicycle)
System.out.println("Instance of Bicycle: True");
else
System.out.println("Instance of Bicycle: False");
if (myBike instanceof TwoWheeled)
System.out.println("Instance of TwoWheeled: True");
else
System.out.println("Instance of TwoWheeled: False");
if (myBike instanceof Vehicle)
System.out.println("Instance of Vehicle: True");
else
System.out.println("Instance of Vehicle: False");
if (myBike instanceof Object)
System.out.println("Instance of Object: True");
else
System.out.println("Instance of Object: False");
}
}
The output is as follows:

Driver class output
As you can see in the preceding screenshot, an instance of the Bicycle class is also an instance of TwoWheeled, Vehicle, and Object. This makes the myBike object polymorphic.
推薦閱讀
- MySQL高可用解決方案:從主從復(fù)制到InnoDB Cluster架構(gòu)
- 文本數(shù)據(jù)挖掘:基于R語言
- 云計(jì)算服務(wù)保障體系
- 文本挖掘:基于R語言的整潔工具
- 金融商業(yè)算法建模:基于Python和SAS
- 大數(shù)據(jù)架構(gòu)商業(yè)之路:從業(yè)務(wù)需求到技術(shù)方案
- 數(shù)字IC設(shè)計(jì)入門(微課視頻版)
- 從實(shí)踐中學(xué)習(xí)sqlmap數(shù)據(jù)庫注入測試
- 算力經(jīng)濟(jì):從超級計(jì)算到云計(jì)算
- 云原生架構(gòu):從技術(shù)演進(jìn)到最佳實(shí)踐
- 數(shù)字化轉(zhuǎn)型方法論:落地路徑與數(shù)據(jù)中臺
- Redis 6開發(fā)與實(shí)戰(zhàn)
- 大學(xué)計(jì)算機(jī):理解和運(yùn)用計(jì)算思維
- Working with OpenERP
- 創(chuàng)新求索錄:第二集(精裝版)