Polymorphism in Java is a difficult concept, but at the same time is a very important concept, Java three major features (encapsulation, inheritance, polymorphism) One, we literally understand, is a type of a variety of states, once again by selling car examples of what is polymorphic, which takes advantage of the interface.
code example:
// Automotive Interface Interface car{ // Requirements Interface: Car name and price String getName (); int GetPrice (); }
//BMW ClassclassBMWImplementscar{@Override PublicString GetName () {//TODO auto-generated Method Stub//return null; returnbmw; } @Override Public intGetPrice () {//TODO auto-generated Method Stub//return 0; return300000; } }//Chery QQclassCheryqqImplementscar{@Override PublicString GetName () {//TODO auto-generated Method Stub return"Chery QQ"; } @Override Public intGetPrice () {//TODO auto-generated Method Stub return40000; } }
//Car Selling Shopclasscarshop{//Income Private intMoney=0; //Sell a car Public voidSellcar (car car) {System.out.println ("Model:" +car.getname () + "Price:" +Car.getprice ()); //increase the selling price of the car revenuemoney+=Car.getprice (); } //Total Car Sales Public intGetmoney () {returnMoney ; }}
Test class:
Public class Jiekoudemo { publicstaticvoid Main (String[]args) { Carshop Shop =new carshop (); // sell a BMW Shop.sellcar (new BMW ()); // sell a Chery QQ Shop.sellcar (new cheryqq ()); System.out.println ("total revenue:" +Shop.getmoney ());} }
Summary of Precautions:
Inheritance is the basis for the realization of polymorphism. Literally, polymorphism is a type (all car type) that shows a variety of states (BMW's name is BMW, the price is 300000; Chery's name is CHERYQQ and the price is 40000). Associating a method call with the subject (i.e. object or class) to which the method belongs is called binding.
Bindings are divided into: early binding and late binding.
1. Early binding: Binding before the program is run, implemented by the compiler and the linker, also known as static binding. such as the static method and the final method. Note that this also includes the private method, because he is implicitly final.
2. Late binding: Binds to the type of the object at run time. is implemented by the invocation mechanism, and is therefore called dynamic binding, or runtime binding. All methods except pre-binding are late-bound.
How interfaces in Java implement polymorphic features