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

Polymorphism

In broad terms, polymorphism gives us an option to use the same interface for entities of different types. There are two major types of polymorphism, compile time and runtime. Say you have a Shape class that has two area methods. One returns the area of a circle and it accepts single integer; that is, the radius is input and it returns the area. Another method calculates the area of a rectangle and takes two inputs, length and breadth. The compiler can decide, based on the number of arguments in the call, which area method is to be called. This is the compile-time type of polymorphism.

There is a group of techies who consider only runtime polymorphism as real polymorphism. Runtime polymorphism, also sometimes known as subtyping polymorphism, comes into play when a subclass inherits a superclass and overrides its methods. In this case, the compiler cannot decide whether the subclass implementation or superclass implementation will be finally executed, and hence a decision is taken at runtime.

To elaborate, let's take our previous example and add a new method to the vehicle type to print the type and name of the object:

public String toString()
{
return "Vehicle:"+name;
}

We override the same method in the derived Car class:

public String toString()
{
return "Car:"+name;
}

Now we can see subtyping polymorphism in action. We create one Vehicle object and one Car object. We assign each object to a Vehicle variable type because a Car is also a Vehicle. Then we invoke the toString method for each of the objects. For vehicle1, which is an instance of the Vehicle class, it will invoke the Vehicle.toString() class. For vehicle2, which is an instance of the Car class, the toString method of the Car class will be invoked:

Vehicle vehicle1 = new Vehicle("A Vehicle");
Vehicle vehicle2 = new Car("A Car")
System.out.println(vehicle1.toString());
System.out.println(vehicle2.toString());
主站蜘蛛池模板: 安新县| 宁德市| 高清| 绩溪县| 义乌市| 湖州市| 苗栗县| 乡城县| 怀远县| 甘南县| 凯里市| 缙云县| 老河口市| 邛崃市| 沁源县| 马龙县| 辽源市| 扶沟县| 时尚| 莱芜市| 彰化县| 张北县| 仁化县| 石林| 延寿县| 林口县| 淮南市| 衡南县| 固原市| 通榆县| 临颍县| 广德县| 大丰市| 正镶白旗| 九江县| 黑龙江省| 丹东市| 凌海市| 康马县| 三门峡市| 阿勒泰市|