官术网_书友最值得收藏!

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:

  1. First, we create a Vehicle class that, by default, extends Java's Object class.
  2. Next, we create a TwoWheeled class that extends the Vehicle class.
  3. Then, we create a Bicycle class that extends the TwoWheeled class.
  1. 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. 

主站蜘蛛池模板: 镇巴县| 瓮安县| 汾阳市| 金坛市| 金堂县| 怀宁县| 长春市| 深泽县| 含山县| 琼结县| 太白县| 武山县| 新和县| 永嘉县| 三台县| 大丰市| 泰州市| 峨边| 佛山市| 忻州市| 屯门区| 大厂| 鹤岗市| 苍南县| 茶陵县| 张家口市| 柳江县| 伊宁市| 清水河县| 七台河市| 和顺县| 监利县| 扎鲁特旗| 济阳县| 尉氏县| 芒康县| 定襄县| 湘潭县| 闸北区| 邢台市| 大冶市|